Python dir() — A Simple Guide with Video - Finxter

文章推薦指數: 80 %
投票人數:10人

If used without argument, Python's built-in dir() function returns the function and variable names defined in the local scope—the namespace of your current ... Skiptocontent Menu Ifusedwithoutargument,Python’sbuilt-indir()functionreturnsthefunctionandvariablenamesdefinedinthelocalscope—thenamespaceofyourcurrentmodule.Ifusedwithanobjectargument,dir(object)returnsalistofattributeandmethodnamesdefinedintheobject’sscope.Thus,dir()returnsallnamesinagivenscope. TableofContents UsageVideodir()Syntaxdir()InteractiveShellExercise:Understandingdir()Usingdir()onModulesOverwritingdir()with__dir__()SummaryWheretoGoFromHere? Usage Learnbyexample!Herearesomeexamplesofhowtousethedir()built-infunction. Here’stheusewithoutanargument: alice=22 bob=42 print(dir()) Itprintstheimplicitlyandexplicitlydefinednamesinyourmodulewhereyourunthiscode: ['__annotations__','__builtins__','__doc__','__file__','__loader__','__name__','__package__','__spec__','alice','bob'] Thelasttwovaluesinthelistarethenames'alice'and'bob'. Thefollowingcodeexemplifiestheuseofdir()withanobjectargumentofclassCar. classCar: speed=100 color='black' porsche=Car() print(dir(porsche)) TheclassCarhastwoattributes.IfyouprintthenamesoftheporscheinstanceoftheCarclass,youobtainthefollowingoutput: ['__class__','__delattr__','__dict__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__gt__','__hash__','__init__','__init_subclass__','__le__','__lt__','__module__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','__weakref__','color','speed'] Thefinaltwoattributesare'color'and'speed',theonesyoudefined.Therearemanyothernamesinthelistwiththedoubleunderscore(calleddunder).ThesearetheattributeandmethodnamesalreadydefinedimplicitlybythePythonenvironmentforanyobject.Forexample,__str__givesthedefaultstringrepresentationofagivenobject. Videodir() Syntaxdir() Syntax: dir()->namesdefinedinthelocalscope/namespace. dir(object)->namesdefinedfortheobject. ArgumentsobjectTheobjectforwhichthenamesshouldbereturned.ReturnValuelistReturnsallnamesdefinedinthenamespaceofthespecifiedobject.Ifnoobjectargumentisgiven,itreturnsthenamesdefinedinthelocalnamespaceofthemoduleinwhichyourunthecode. InteractiveShellExercise:Understandingdir() Considerthefollowinginteractivecode: Exercise:Guesstheoutputbeforerunningthecode.Dobothcars,porscheandtesla,generatethesameoutput? Butbeforewemoveon,I’mexcitedtopresentyoumynewPythonbookPythonOne-Liners(AmazonLink). Ifyoulikeone-liners,you’llLOVEthebook.It’llteachyoueverythingthereistoknowaboutasinglelineofPythoncode.Butit’salsoanintroductiontocomputerscience,datascience,machinelearning,andalgorithms.TheuniverseinasinglelineofPython! Thebookwasreleasedin2020withtheworld-classprogrammingbookpublisherNoStarchPress(SanFrancisco). Link:https://nostarch.com/pythononeliners Usingdir()onModules YoucanalsousePython’sbuilt-indir()methodonmodules.Forexample,afterimportingtherandommodule,youcanpassitintothedir(random)function.Thisgivesyouallthenamesandfunctionsdefinedinthemodule. importrandom print("Therandommodulecontainsthefollowingnames:") print(dir(random)) Theoutputisthefollowing: Therandommodulecontainsthefollowingnames: ['BPF','LOG4','NV_MAGICCONST','RECIP_BPF','Random','SG_MAGICCONST','SystemRandom','TWOPI','_BuiltinMethodType','_MethodType','_Sequence','_Set','__all__','__builtins__','__cached__','__doc__','__file__','__loader__','__name__','__package__','__spec__','_acos','_bisect','_ceil','_cos','_e','_exp','_inst','_itertools','_log','_os','_pi','_random','_sha512','_sin','_sqrt','_test','_test_generator','_urandom','_warn','betavariate','choice','choices','expovariate','gammavariate','gauss','getrandbits','getstate','lognormvariate','normalvariate','paretovariate','randint','random','randrange','sample','seed','setstate','shuffle','triangular','uniform','vonmisesvariate','weibullvariate'] Thisway,youcanquicklyexplorethecontentsofamoduleandwhichfunctionsyoumaywanttouseinyourowncode! Overwritingdir()with__dir__() Tocustomizethereturnvalueofthedir()functiononacustomclass,youcanoverwritethe__dir__()methodandreturnthevaluestobereturned.Thisway,youcanhidenamesfromtheuserorfilteroutonlyrelevantnamesofyourobject. classCar: speed=100 color='gold' def__dir__(self): return['porsche','tesla','bmw'] tesla=Car() print(dir(tesla)) Theoutputisthenonsensicallistof“names”: ['bmw','porsche','tesla'] Summary Therearetwodifferentusecasesforthedir()function. Ifusedwithoutargument,Python’sbuilt-indir()functionreturnsthefunctionandvariablenamesdefinedinthelocalscope—thenamespaceofyourcurrentmodule.Ifusedwithanobjectargument,dir(object)returnsalistofattributeandmethodnamesdefinedintheobject’sscope. Thus,dir()returnsallnamesinagivenscope. Source:Documentation Ihopeyouenjoyedthearticle!ToimproveyourPythoneducation,youmaywanttojointhepopularfreeFinxterEmailAcademy: DoyouwanttoboostyourPythonskillsinafunandeasy-to-consumeway?Considerthefollowingresourcesandbecomeamastercoder! WheretoGoFromHere? Enoughtheory.Let’sgetsomepractice! Codersgetpaidsixfiguresandmorebecausetheycansolveproblemsmoreeffectivelyusingmachineintelligenceandautomation. Tobecomemoresuccessfulincoding,solvemorerealproblemsforrealpeople.That’showyoupolishtheskillsyoureallyneedinpractice.Afterall,what’stheuseoflearningtheorythatnobodyeverneeds? Youbuildhigh-valuecodingskillsbyworkingonpracticalcodingprojects! Doyouwanttostoplearningwithtoyprojectsandfocusonpracticalcodeprojectsthatearnyoumoneyandsolverealproblemsforpeople? 🚀IfyouranswerisYES!,considerbecomingaPythonfreelancedeveloper!It’sthebestwayofapproachingthetaskofimprovingyourPythonskills—evenifyouareacompletebeginner. Ifyoujustwanttolearnaboutthefreelancingopportunity,feelfreetowatchmyfreewebinar“HowtoBuildYourHigh-IncomeSkillPython”andlearnhowIgrewmycodingbusinessonlineandhowyoucan,too—fromthecomfortofyourownhome. Jointhefreewebinarnow! ChrisWhileworkingasaresearcherindistributedsystems,Dr.ChristianMayerfoundhisloveforteachingcomputersciencestudents. TohelpstudentsreachhigherlevelsofPythonsuccess,hefoundedtheprogrammingeducationwebsiteFinxter.com.He’sauthorofthepopularprogrammingbookPythonOne-Liners(NoStarch2020),coauthoroftheCoffeeBreakPythonseriesofself-publishedbooks,computerscienceenthusiast,freelancer,andownerofoneofthetop10largestPythonblogsworldwide. Hispassionsarewriting,reading,andcoding.ButhisgreatestpassionistoserveaspiringcodersthroughFinxterandhelpthemtoboosttheirskills.Youcanjoinhisfreeemailacademyhere. RelatedTutorialsTheUltimateGuidetoPythonListsPythonNamespacesMadeSimple100CodePuzzlestoTrainYourRapidPythonUnderstandingPythonListsort()-TheUltimateGuide56PythonOne-LinerstoImpressYourFriendsPythonOneLineX WhyFinxter? "Givemealeverlongenough[...]andIshallmovetheworld."🌍-Archimedes Finxteraimstobeyourlever!Oursinglepurposeistoincreasehumanity'scollectiveintelligenceviaprogrammingtutorialssoyoucanleverageinfinitecomputationalintelligencetoyoursuccess!🧠 LearningResources Feelfreetojoinourfreeemailacademywith1000+tutorialsinPython,freelancing,datascienceandmachinelearning,andBlockchaintechnology! Also,feelfreetocheckoutourFinxterbooksandtheworld's#1freelancercoursetocreateyourthrivingcodingbusinessonline.⭐⭐⭐⭐⭐ FreelanceCoder Ifyou'renotquitereadytogoallin,readoverourblogarticleonearningyourfirst$3,000asafreelancecoder. ALLSIDEBARLINKSOPENINANEWTAB! NewFinxterTutorials: EasyExploratoryDataAnalysis(EDA)inPythonwithVisualization HowtoCheckifaListHasanEvenNumberofElements? HowtoCheckifaListHasanOddNumberofElements? GameDeveloper—IncomeandOpportunity HowtoFindCommonElementsofTwoLists HowtoSumtwoDataFrameColumns TheMaximumProfitAlgorithminPython Top20SkillsEveryDevOpsEngineerOughttoHave DataScientist—IncomeandOpportunity HowtoConvertTuplestoaCSVFileinPython[4Ways] FinxterCategories: Categories SelectCategory 2-minComputerScienceConcepts 2-minComputerSciencePapers AlexaSkills Algorithms AppDevelopment Arduino ArtificialIntelligence Automation BeautifulSoup Binary Bitcoin Blockchain Blogging Brownie C C# C++ Career CheatSheets Clojure CloudComputing CodingBusiness CodingInterview ComputerScience Crypto CSS DailyDataSciencePuzzle DailyPythonPuzzle Dash DataScience DataStructures DataVisualization Database DependencyManagement DevOps DistributedSystems Django DunderMethods Error Ethereum Excel ExceptionHandling Flask Float Freelancing FunctionalProgramming Functions Git Go GraphTheory GUI Hardware HTML ImageProcessing Input/Output Investment Java JavaScript json Jupyter Keras Linux MachineLearning macOS Math Matplotlib NaturalLanguageProcessing Networking Newspaper3k NFT ObjectOrientation OpenCV OperatingSystem PandasLibrary Performance PHP Pillow pip Powershell Productivity PyCharm PyTest Python PythonBuilt-inFunctions PythonDictionary PythonEmailCourse PythonKeywords PythonList PythonOne-Liners PythonOperators PythonRequests PythonSet PythonString Pythonsys PythonTime PythonTuple PyTorch React Regex Research Scikit-learnLibrary SciPy Scripting Seaborn Security Selenium shutil sklearn SmartContracts Solana Solidity SQL Streamlit SymPy Tableau TensorFlow Testing TextProcessing TheNumpyLibrary TKinter Trading VisualStudio WebDevelopment WebScraping Windows



請為這篇文章評分?