self in Python class - GeeksforGeeks
文章推薦指數: 80 %
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
延伸文章資訊
- 1Python Tutorial: classes and instances - 2021 - BogoToBogo
We are creating an instance of the Student class and assigning the newly created instance to the ...
- 2How to Put Keyword Arguments in your Python Class Definitions
How would someone prompt users to put a keyword argument in their class definitions? Using a Meta...
- 3Python Class Constructors: Control Your Object Instantiation
__init__() method. To this end, one of the most popular techniques is to use optional arguments. ...
- 4Simple function classes - Introduction to classes in Python
Any class method must have self as first argument. · self represents an (arbitrary) instance of t...
- 59. Classes — Python 3.10.7 documentation
When the method object is called with an argument list, a new argument list is constructed from t...