What is the difference between __init__ and __call__?
文章推薦指數: 80 %
In Python, __call__() is used to resolve the code associated with a callable object. Any object can be converted to a callable object just by ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#HTMLJavaScriptPHPSQLScalaPerlGoLanguageKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadafilelinebylineinPythonIterateoveralistinPythonPythonDictionaryPythonprogramtoconvertalisttostringReadingandWritingtotextfilesinPythonPythonString|replace()Enumerate()inPythonDifferentwaystocreatePandasDataframesum()functioninPythonPrintlistsinPython(5DifferentWays)isupper(),islower(),lower(),upper()inPythonandtheirapplicationsConvertintegertostringinPython*argsand**kwargsinPythonPython|GetalistasinputfromuserPythonListsPythonString|split()Python|ProgramtoconvertStringtoaListCreateaPandasDataFramefromListsfloor()andceil()functionPythonGraphPlottinginPython|Set1GETandPOSTrequestsusingPythonTakingmultipleinputsfromuserinPythonFindaverageofalistinpythonStackinPythonPythonStringfind()methodAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadafilelinebylineinPythonIterateoveralistinPythonPythonDictionaryPythonprogramtoconvertalisttostringReadingandWritingtotextfilesinPythonPythonString|replace()Enumerate()inPythonDifferentwaystocreatePandasDataframesum()functioninPythonPrintlistsinPython(5DifferentWays)isupper(),islower(),lower(),upper()inPythonandtheirapplicationsConvertintegertostringinPython*argsand**kwargsinPythonPython|GetalistasinputfromuserPythonListsPythonString|split()Python|ProgramtoconvertStringtoaListCreateaPandasDataFramefromListsfloor()andceil()functionPythonGraphPlottinginPython|Set1GETandPOSTrequestsusingPythonTakingmultipleinputsfromuserinPythonFindaverageofalistinpythonStackinPythonPythonStringfind()methodWhatisthedifferencebetween__init__and__call__?ViewDiscussion ImproveArticle SaveArticle LikeArticle LastUpdated: 21Apr,2020ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle DunderormagicmethodsinPythonarethemethodshavingtwoprefixesandsuffixunderscoresinthemethodname.Dunderheremeans“DoubleUnder(Underscores)”.Thesearecommonlyusedforoperatoroverloading.Fewexamplesformagicmethodsare:__init__,__add__,__len__,__repr__etc.Inthisarticle,wearegoingtoseethedifferencebetweentwosuchmethods.Note:Formoreinformation,refertoDunderormagicmethodsinPython__init__()ThisPythonmethodissimilartoaconstructorinanyotherprogramminglanguage.Aconstructorisadefinitionwiththesamenameastheclassandisinvokedautomaticallywhentheobjectofthatclassisdefined.Aconstructorinitializesalltherequiredentitiesoftheprogramtomakeitmorereliable.Similartothisdefinition__init__()worksasaPythonconstructoritisinvokedautomaticallywhenanobjectoftheclassisdefined.Itinitializestherequiredmemberswithdefaultvaluesprovided.Itcanalsobeinvokedwiththevaluesprovidedduringthetimeofdeclarationoftheobjectoftheclass.EXAMPLE:classA: def__init__(self,x): print("inside__init__()") self.y=x def__str__(self): print("inside__str__()") print("valueofy:",str(self.y)) #declarationofinstanceofclassAa=A(3) #calling__str__()forobjectaa.__str__() #declarationofanotherinstance #ofclassAb=A(10) #calling__str__()forbb.__str__()OUTPUT:inside__init__() inside__str__() ('valueofy:','3') inside__init__() inside__str__() ('valueofy:','10') __call__()Beforegettingintoapplicationof__call__()weneedtounderstandwhatacallableobjectis.Acallableobjectisonewhichcanbecalledlikeafunction.InPython,__call__()isusedtoresolvethecodeassociatedwithacallableobject.Anyobjectcanbeconvertedtoacallableobjectjustbywritingitinafunctioncallformat.Anobjectofthatkindinvokesthe__call__()methodandexecutesthecodeassociatedwithit.Thisdoesn’tmaketheobjectnottoworklikeanormalone.Theobjectcanbeusedasanormalisused.Onethingtokeepinmindistheobjectisitselfusedasafunction,sosyntaxshouldberight.EXAMPLE:classA: def__init__(self,x): print("inside__init__()") self.y=x def__str__(self): print("inside__str__()") print("valueofy:",str(self.y)) def__call__(self): res=0 print("inside__call__()") print("adding2tothevalueofy") res=self.y+2 returnres #declarationofinstanceofclassAa=A(3) #calling__str__()foraa.__str__() #calling__call__()fora r=a()print(r) #declarationofanotherinstance#ofclassAb=A(10) #calling__str__()forbb.__str__() #calling__call__()forbr=b()print(r)OUTPUT:inside__init__() inside__str__() ('valueofy:','3') inside__call__() adding2tothevalueofy 5 inside__init__() inside__str__() ('valueofy:','10') inside__call__() adding2tothevalueofy 12Differencebetween__init__()VS__call__()__init__()__call__()Sameasaconstructor,itinitializesthevaluesItisusedforadirectcallusingtheobjectItisinvokedautomaticallywhenanobjectisdeclaredItisinvokedautomaticallybyacallableCalledbyanregularobjectCalledbyacallableobjectExample:a=A(3)#statement1a()#statement2__init__()iscalledbystatement1Example:a=A(3)#statement1a()#statement2__call__()iscalledbystatement2MyPersonalNotes arrow_drop_upSave LikePreviousPyQt5-AccessthesizeofStatusBarNext PyQt5-AddpaddingtoStatusBarRecommendedArticlesPage:27,Jan2015,Apr1909,Nov1804,Dec1923,Dec1921,Jan2024,Feb2005,May2025,Jul2002,Apr2018,Dec1722,Jun2001,Aug1807,Jan1909,Jan2112,Aug1927,Jul2114,Jan2020,Jan2026,Feb2024,Feb2005,Mar2007,May2030,Mar20ArticleContributedBy:vanshikagoyal43@vanshikagoyal43VotefordifficultyEasy Normal Medium Hard ExpertArticleTags:python-oop-conceptsPythonPracticeTags:pythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register
延伸文章資訊
- 1__init__ in Python: An Overview | Udacity
The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approac...
- 2__init__ in Python - Python Morsels
Python calls __init__ whenever a class is called
- 3Use of the __init__() Function in Python - Linux Hint
The __init__() function works like the constructor method in Python and is declared inside the cl...
- 4Is it possible to init a class and call a method at the same time ...
__init__ (double underscore “init” followed by double underscore), when it's used as the name of ...
- 5Calling a class function inside of __init__ - Stack Overflow
Is there a way to call a class function from within __init__ of that class? Or am I thinking abou...