self in Python class - GeeksforGeeks

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

Self is the first argument to be passed in Constructor and Instance Method. Self must be provided as a First parameter to the Instance method ... 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 ▲RelatedArticles__init__inPythonselfinPythonclassClassmethodvsStaticmethodinPythonClassorStaticVariablesinPythonChangingClassMembersinPythonConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonAbstractClassesinPythonDefaultdictinPythonPythonmap()functionreduce()inPythonfilter()inpythonPythonLambdaFunctionsLambdaandfilterinPythonExamplesIntersectionoftwoarraysinPython(Lambdaexpressionandfilterfunction)G-Fact19(LogicalandBitwiseNotOperatorsonBoolean)TernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1AddingnewcolumntoexistingDataFrameinPandasReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframe__init__inPythonselfinPythonclassClassmethodvsStaticmethodinPythonClassorStaticVariablesinPythonChangingClassMembersinPythonConstructorsinPythonDestructorsinPythonInheritanceinPythonTypesofinheritancePythonEncapsulationinPythonPolymorphisminPythonAbstractClassesinPythonDefaultdictinPythonPythonmap()functionreduce()inPythonfilter()inpythonPythonLambdaFunctionsLambdaandfilterinPythonExamplesIntersectionoftwoarraysinPython(Lambdaexpressionandfilterfunction)G-Fact19(LogicalandBitwiseNotOperatorsonBoolean)TernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1AddingnewcolumntoexistingDataFrameinPandasReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframeselfinPythonclassViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 22Apr,2022ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle selfrepresentstheinstanceoftheclass.Byusingthe“self” wecanaccesstheattributesandmethodsoftheclassinpython.Itbindstheattributeswiththegivenarguments.Thereasonyouneedtouseself.isbecausePythondoesnotusethe@syntaxtorefertoinstanceattributes.Pythondecidedtodomethodsinawaythatmakestheinstancetowhichthemethodbelongsbepassedautomatically,butnotreceivedautomatically:thefirstparameterofmethodsistheinstancethemethodiscalledon.InmoreclearwayyoucansaythatSELFhasfollowingCharacteristic-SelfisalwayspointingtoCurrentObject.Python3#itisclearlyseenthatselfandobjisreferringtothesameobject classcheck:    def__init__(self):        print("Addressofself=",id(self)) obj=check()print("Addressofclassobject=",id(obj)) #thiscodeisContributedbySamyakJainOutputAddressofself=140124194801032 Addressofclassobject=140124194801032AnotherExampleofUsingSELF:Python3#WritePython3codehere classcar():         #initmethodorconstructor    def__init__(self,model,color):        self.model=model        self.color=color             defshow(self):        print("Modelis",self.model)        print("coloris",self.color)         #bothobjectshavedifferentselfwhich#containtheirattributesaudi=car("audia4","blue")ferrari=car("ferrari488","green") audi.show()    #sameoutputascar.show(audi)ferrari.show() #sameoutputascar.show(ferrari) #Behindthescene,ineveryinstancemethod#call,pythonsendstheinstancesalsowith#thatmethodcalllikecar.show(audi)OutputModelisaudia4 colorisblue Modelisferrari488 colorisgreenSelfisthefirstargumenttobepassedinConstructorandInstanceMethod.SelfmustbeprovidedasaFirstparametertotheInstancemethodandconstructor.Ifyoudon’tprovideit,itwillcauseanerror.Python3#Selfisalwaysrequiredasthefirstargumentclasscheck:    def__init__():        print("ThisisConstructor") object=check()print("Workedfine")  #FollowingErrorisproducedifSelfisnotpassedasanargumentTraceback(mostrecentcalllast):  File"/home/c736b5fad311dd1eb3cd2e280260e7dd.py",line6,in    object=check()TypeError:__init__()takes0positionalargumentsbut1wasgiven        #thiscodeisContributedbySamyakJainSelfisaconventionandnotaPythonkeyword .selfisparameterinInstanceMethodandusercanuseanotherparameternameinplaceofit.Butitisadvisabletouseselfbecauseitincreasesthereadabilityofcode,anditisalsoagoodprogrammingpractice.Python3#WritePython3codehere classthis_is_class:    def__init__(in_place_of_self):        print("wehaveusedanother"        "parameternameinplaceofself")         object=this_is_class()OutputwehaveusedanotherparameternameinplaceofselfMyPersonalNotes arrow_drop_upSave LikePrevious__init__inPythonNext ClassmethodvsStaticmethodinPythonRecommendedArticlesPage:14,Aug2012,Dec1901,Jul2015,Jul2008,Jul2003,Jan2120,Feb1611,Feb1620,May1701,Apr2001,Nov1705,Apr2023,Aug2105,Apr2004,Sep1831,Aug1812,Apr2024,Jan2220,Nov1807,Jan1924,Jan1915,Feb1912,Jun1913,Jun19ArticleContributedBy:gyanendra371@gyanendra371VotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:sudhansan5iamsamyaksimmytarika5simranarora5sossaurabh1990aroradityakh97ArticleTags:Python-OOPpython-oop-conceptsPythonPracticeTags:pythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?