dir() Method in Python - Tutorialspoint

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

When we print the value of the dir() without importing any other module into the program, we get the list of methods and attributes that are ... TrendingCategories DataStructure Networking RDBMS OperatingSystem Java iOS HTML CSS Android Python CProgramming C++ C# MongoDB MySQL Javascript PHP SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho dir()MethodinPython PythonServerSideProgrammingProgramming Thedir()functionreturnslistoftheattributesandmethodsofanyobjectlikefunctions,modules,strings,lists,dictionariesetc.Inthisarticlewewillseehowtousethedir()indifferentwaysinaprogramandfordifferentrequirements.Onlydir()Whenweprintthevalueofthedir()withoutimportinganyothermoduleintotheprogram,wegetthelistofmethodsandattributesthatareavailableaspartofthestandardlibrarythatisavailablewhenapythonprogramisinitialized.ExamplePrint(dir())OutputRunningtheabovecodegivesusthefollowingresult−['__annotations__','__builtins__','__cached__','__doc__','__file__','__loader__','__name__','__package__','__spec__']AdditionalmodulesAsweimportadditionalmodulesandcreatevariables,theygetaddedtothecurrentenvironment.Thenthosemethodsandattributesalsobecomeavailableintheprintstatementwothdir().Exampleimportmath x=math.ceil(10.03) print(dir())OutputRunningtheabovecodegivesusthefollowingresult−['__annotations__','__builtins__','__cached__','__doc__','__file__','__loader__','__name__','__package__','__spec__','math','x']dir()forspecificModulesForspecificmoduleswecanfindthemethodsandattributescontainedinthatmodulebypassingitasparametertothedir().Inthebelowexampleweseethemethodsavailableinthemathmodule.Exampleimportmath print(dir(math))OutputRunningtheabovecodegivesusthefollowingresult−['__doc__','__loader__','__name__','__package__','__spec__','acos','acosh','asin','asinh','atan','atan2','atanh','ceil','copysign',….,'nan',…'trunc']dir()foraclassWecanalsoapplythedir()toaclasswhichwasusercreatedratherthanin-bulitandgetsitsattributeslistedthroughdir().Example LiveDemoclassmoviecount:   def__dir__(self):    return['RedMan','HelloBoy','HappyMonday'] movie_dtls=moviecount() print(dir(movie_dtls))OutputRunningtheabovecodegivesusthefollowingresult−['HappyMonday','HelloBoy','RedMan'] PradeepElance Publishedon26-Aug-202007:03:18 RelatedQuestions&AnswersThedir()FunctioninPython HTMLdirAttribute HTMLDOMdirproperty HTMLDOMBdodirProperty Whatisthedifferencebetweendir(),globals()andlocals()functionsinPython? ClassmethodvsstaticmethodinPython evalmethodinPython? numpy.vanderMethodinPython numpy.matrixMethodinPython numpy.trilMethodinPython numpy.triuMethodinPython numpy.triMethodinPython Python-getattr()method Python-cmp()Method Python-iter()method PreviousPage PrintPage NextPage  Advertisements Print  AddNotes  Bookmarkthispage  ReportError  Suggestions Save Close Dashboard Logout



請為這篇文章評分?