dir() function in Python - GeeksforGeeks

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

dir() is a powerful inbuilt function in Python3, which returns list of the attributes and methods of any object (say functions , modules, ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryMust-DoCodingQuestionsExploreMoreForStudentsLIVECompetitiveProgrammingDataStructureswithC++DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsPracticeDS&Algo.MustDoQuestionsDSATopic-wiseDSACompany-wiseAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsGeekontheTopCareersInternshipJobsApplyforJobsPostaJobJOB-A-THONEvents ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningHTMLSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesresponse.text–Pythonrequestsresponse.headers–Pythonrequestsresponse.cookies–PythonrequestsSessionObjects–Pythonrequestsvars()functioninPythonDifferencebetweendir()andvars()inPythondir()functioninPythonHelpfunctioninPythonPython|__import__()functionPython|range()doesnotreturnaniteratorTop10UsefulGitHubReposThatEveryDeveloperShouldFollow5GitHubRepositoriesthatEveryNewDeveloperMustFollowFetchtop10starredrepositoriesofuseronGitHub|PythonAuthenticationusingPythonrequestsGETandPOSTrequestsusingPythonPOSTmethod–PythonrequestsGETmethod–Pythonrequestsresponse.json()–Pythonrequestsresponse.content–PythonrequestsResponseMethods–PythonrequestsAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadJSONfileusingPythonPythonprogramtoconvertalisttostringReadafilelinebylineinPythonIterateoveralistinPythonReadingandWritingtotextfilesinPythonPythonDictionaryTableofContentsresponse.text–Pythonrequestsresponse.headers–Pythonrequestsresponse.cookies–PythonrequestsSessionObjects–Pythonrequestsvars()functioninPythonDifferencebetweendir()andvars()inPythondir()functioninPythonHelpfunctioninPythonPython|__import__()functionPython|range()doesnotreturnaniteratorTop10UsefulGitHubReposThatEveryDeveloperShouldFollow5GitHubRepositoriesthatEveryNewDeveloperMustFollowFetchtop10starredrepositoriesofuseronGitHub|PythonAuthenticationusingPythonrequestsGETandPOSTrequestsusingPythonPOSTmethod–PythonrequestsGETmethod–Pythonrequestsresponse.json()–Pythonrequestsresponse.content–PythonrequestsResponseMethods–PythonrequestsAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadJSONfileusingPythonPythonprogramtoconvertalisttostringReadafilelinebylineinPythonIterateoveralistinPythonReadingandWritingtotextfilesinPythonPythonDictionaryImproveArticle SaveArticle LikeArticle dir()functioninPythonDifficultyLevel: EasyLastUpdated: 21Jun,2021dir()isapowerfulinbuiltfunctioninPython3,whichreturnslistoftheattributesandmethodsofanyobject(sayfunctions,modules,strings,lists,dictionariesetc.)Syntax:  dir({object})Parameters:  object[optional]:Takesobjectname Returns:dir()triestoreturnavalidlistofattributesoftheobjectitiscalledupon.Also,dir()functionbehavesratherdifferentlywithdifferenttypeofobjects,asitaimstoproducethemostrelevantone,ratherthanthecompleteinformation.  ForClassObjects,itreturnsalistofnamesofallthevalidattributesandbaseattributesaswell.  ForModules/Libraryobjects,ittriestoreturnalistofnamesofalltheattributes,containedinthatmodule.  Ifnoparametersarepasseditreturnsalistofnamesinthecurrentlocalscope.  Code#1:WithandWithoutimportingexternallibraries. Python3#Python3codetodemonstratedir()#whennoparametersarepassed #Notethatwehavenotimportedanymodulesprint(dir())  #Nowlet'simporttwomodulesimportrandomimportmath #returnthemodulenamesaddedto#thelocalnamespaceincludingall#theexistingonesasbeforeprint(dir())Output:   ['__builtins__','__cached__','__doc__','__file__','__loader__', '__name__','__package__','__spec__'] ['__builtins__','__cached__','__doc__','__file__','__loader__', '__name__','__package__','__spec__','math','random']  Code#2:  Python3#Python3codetodemonstratedir()function#whenamoduleObjectispassedasparameter. #importtherandommoduleimportrandom  #Printslistwhichcontainsnamesof#attributesinrandomfunctionprint("Thecontentsoftherandomlibraryare::") #moduleObjectispassedasparameterprint(dir(random))Output:  Thecontentsoftherandomlibraryare:: ['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','_ceil','_cos','_e','_exp', '_inst','_log','_pi','_random','_sha512','_sin','_sqrt','_test','_test_generator', '_urandom','_warn','betavariate','choice','expovariate','gammavariate','gauss', 'getrandbits','getstate','lognormvariate','normalvariate','paretovariate','randint', 'random','randrange','sample','seed','setstate','shuffle','triangular','uniform', 'vonmisesvariate','weibullvariate']  Code#3:Objectispassedasparameters. Python3#Whenalistobjectispassedas#parametersforthedir()function #Alist,whichcontains#afewrandomvaluesgeeks=["geeksforgeeks","gfg","ComputerScience",                    "DataStructures","Algorithms"]  #dir()willalsolistoutcommon#attributesofthedictionaryd={}  #emptydictionary #dir()willreturnalltheavailable#listmethodsincurrentlocalscopeprint(dir(geeks))  #Calldir()withthedictionary#name"d"asparameter.Returnall#theavailabledictmethodsinthe#currentlocalscopeprint(dir(d))Output:  ['__add__','__class__','__contains__','__delattr__','__delitem__', '__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__', '__getitem__','__gt__','__hash__','__iadd__','__imul__','__init__', '__iter__','__le__','__len__','__lt__','__mul__','__ne__','__new__', '__reduce__','__reduce_ex__','__repr__','__reversed__','__rmul__','__setattr__', '__setitem__','__sizeof__','__str__','__subclasshook__','append','clear', 'copy','count','extend','index','insert','pop','remove','reverse','sort'] ['__class__','__contains__','__delattr__','__delitem__','__dir__','__doc__', '__eq__','__format__','__ge__','__getattribute__','__getitem__','__gt__', '__hash__','__init__','__iter__','__le__','__len__','__lt__','__ne__', '__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__setitem__', '__sizeof__','__str__','__subclasshook__','clear','copy','fromkeys','get','items', 'keys','pop','popitem','setdefault','update','values']  Code#4:UserDefined–ClassObjectwithanavailable__dir()__methodispassedasparameter.  Python3#Python3programtodemonstrateworking#ofdir(),whenuserdefinedobjectsare#passedareparameters.  #Creationofasimpleclasswith__dir()__#methodtodemonstrateit'sworkingclassSupermarket:     #Function__dir()___whichlistall    #thebaseattributestobeused.    def__dir__(self):        return['customer_name','product',               'quantity','price','date']  #user-definedobjectofclasssupermarketmy_cart=Supermarket() #listingoutthedir()methodprint(dir(my_cart))Output:  ['customer_name','date','price','product','quantity']  Applications:  Thedir()hasit’sownsetofuses.Itisusuallyusedfordebuggingpurposesinsimpledaytodayprograms,andeveninlargeprojectstakenupbyateamofdevelopers.Thecapabilityofdir()tolistoutalltheattributesoftheparameterpassed,isreallyusefulwhenhandlingalotofclassesandfunctions,separately.  Thedir()functioncanalsolistoutalltheavailableattributesforamodule/list/dictionary.So,italsogivesusinformationontheoperationswecanperformwiththeavailablelistormodule,whichcanbeveryusefulwhenhavinglittletonoinformationaboutthemodule.Italsohelpstoknownewmodulesfaster.   MyPersonalNotes arrow_drop_upSave LikePreviousDifferencebetweendir()andvars()inPythonNext HelpfunctioninPythonRecommendedArticlesPage:05,May2004,Dec1927,Apr2001,Sep2002,Jun2004,May1615,May1610,May1722,Jun1716,Jul1727,Jul1710,Jan1803,Apr1903,Apr1910,Jan1828,Oct1722,Nov1724,Nov1725,Nov1725,Nov1727,Nov1730,Nov1712,Dec1713,Dec17ArticleContributedBy:retr0@retr0VotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:shubham_singhgabaa406ArticleTags:Python-Built-in-functionsPythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinPythonEnumerate()inPythonHowtoInstallPIPonWindows?DifferentwaystocreatePandasDataframePythonString|replace()CreateaPandasDataFramefromListsMorerelatedarticlesinPython*argsand**kwargsinPythonHowToConvertPythonDictionaryToJSON?sum()functioninPythonHowtodroponeormultiplecolumnsinPandasDataframePrintlistsinPython(4DifferentWays)× Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?