Python Classes and Objects - DigitalOcean
文章推薦指數: 80 %
Python is an object-oriented programming language. Python Classes and Objects are the core building blocks of Python programming language. Getalertedwhenassetsaredown,slow,orvulnerabletoSSLattacks—allfreeforamonth.LearnmoreProductsPricingDocsSigninTutorialsQuestionsLearningPathsTechTalksGetInvolvedProductDocsSearchCommunity/SignUpCONTENTSPythonClassSimplePythonClassDeclarationPythonClassDefinitionPythonClassVariablesPythonClassConstructorPythonClassMethodsPythonClassObjectRelatedHowToSetupuWSGIOnUbuntu12.10ViewHowToCreateNagiosPluginsWithPythonOnCentOS6View//Tutorial//PythonClassesandObjectsPublishedonAugust3,2022PythonByPankajDeveloperandauthoratDigitalOcean.Whilewebelievethatthiscontentbenefitsourcommunity,wehavenotyetthoroughlyreviewedit.Ifyouhaveanysuggestionsforimprovements,pleaseletusknowbyclickingthe“reportanissue“buttonatthebottomofthetutorial.Pythonisanobject-orientedprogramminglanguage.PythonClassesandObjectsarethecorebuildingblocksofPythonprogramminglanguage. PythonClass Bythistime,allofyoushouldhavealreadylearnedaboutPythonDataTypes.Ifyouremember,basicdatatypesinpythonrefertoonlyonekindofdataatatime.Howwoulditbeifyoucoulddeclareadatatypewhichitselfcontainsmorethanonedatatypesandcanworkwiththemwiththehelpofanyfunction?Pythonclassgivesyouthatopportunity.Pythonclassistheblueprintonwhichinstancesoftheclassarecreated. SimplePythonClassDeclaration Here’stheverybasicstructureofpythonclassdefinition. classClassName: #listofpythonclassvariables #pythonclassconstructor #pythonclassmethoddefinitions Now,let’sworkwithrealexamples. #definitionoftheclassstartshere classPerson: #initializingthevariables name="" age=0 #definingconstructor def__init__(self,personName,personAge): self.name=personName self.age=personAge #definingclassmethods defshowName(self): print(self.name) defshowAge(self): print(self.age) #endoftheclassdefinition #Createanobjectoftheclass person1=Person("John",23) #Createanotherobjectofthesameclass person2=Person("Anne",102) #callmembermethodsoftheobjects person1.showAge() person2.showName() Thisexampleisprettymuchself-explanatory.Asweknow,thelinesstartingwith“#”arepythoncomments.Thecommentsexplainthenextexecutablesteps.Thiscodeproducesthefollowingoutput. PythonClassDefinition classPerson: Thislinemarksthebeginningofclassdefinitionforclass‘Person’. PythonClassVariables #initializingthevariables name="" age=0 ‘name’and‘age’aretwomembervariablesoftheclass‘Person’.Everytimewedeclareanobjectofthisclass,itwillcontainthesetwovariablesasitsmember.Thispartisoptionalastheycanbeinitializedbytheconstructor. PythonClassConstructor #definingconstructor def__init__(self,personName,personAge): self.name=personName self.age=personAge Pythonclassconstructoristhefirstpieceofcodetobeexecutedwhenyoucreateanewobjectofaclass.Primarily,theconstructorcanbeusedtoputvaluesinthemembervariables.Youmayalsoprintmessagesintheconstructortobeconfirmedwhethertheobjecthasbeencreated.Weshalllearnagreaterroleofconstructoroncewegettoknowaboutpythoninheritance.Theconstructormethodstartswithdef__init__.Afterward,thefirstparametermustbe‘self’,asitpassesareferencetotheinstanceoftheclassitself.Youcanalsoaddadditionalparameterslikethewayitisshownintheexample.‘personName’and‘personAge’aretwoparameterstosentwhenanewobjectistobecreated. PythonClassMethods #definingpythonclassmethods defshowName(self): print(self.name) Methodsaredeclaredinthefollowingway: defmethod_name(self,parameter1,parameter2,…….) statements…….. returnvalue(ifrequired) Inthepre-statedexample,we’veseenthatthemethodshowName()printsvalueof‘name’ofthatobject.Weshalldiscussalotmoreaboutpythonmethodssomeotherday. PythonClassObject #Createanobjectoftheclass person1=Person("Richard",23) #Createanotherobjectofthesameclass person2=Person("Anne",30) #callmembermethodsoftheobjects person1.showAge() person2.showName() Thewayobjectsarecreatedinpythonisquitesimple.Atfirst,youputthenameofthenewobjectwhichisfollowedbytheassignmentoperatorandthenameoftheclasswithparameters(asdefinedintheconstructor).Remember,thenumberandtypeofparametersshouldbecompatiblewiththeparametersreceivedintheconstructorfunction.Whentheobjecthasbeencreated,membermethodscanbecalledandmemberattributescanbeaccessed(providedtheyareaccessible). #printthenameofperson1bydirectlyaccessingthe‘name’attribute print(person1.name) That’sallforthebasicsofpythonclass.Aswearegoingtolearnaboutpythonobject-orientedfeatureslikeinheritance,polymorphisminthesubsequenttutorials,weshalllearnmoreaboutpythonclassanditsfeatures.Tillthen,happycodingandgoodbye!Feelfreetocommentifyouhaveanyquery.Reference:Python.orgDocumentation Wanttolearnmore?JointheDigitalOceanCommunity!JoinourDigitalOceancommunityofoveramilliondevelopersforfree!GethelpandshareknowledgeinourQuestions&Answerssection,findtutorialsandtoolsthatwillhelpyougrowasadeveloperandscaleyourprojectorbusiness,andsubscribetotopicsofinterest.SignupAbouttheauthorsPankajauthorDeveloperandauthoratDigitalOcean.Stilllookingforananswer?AskaquestionSearchformorehelpWasthishelpful?YesNoCommentsJournalDev•October20,2020Pythonclassconstructortoinitialise2Darray -kavitha JournalDev•May25,2020#Createanobjectoftheclassperson1=Person(“John”,23)#Createanotherobjectofthesameclassperson2=Person(“Anne”,102)#callmembermethodsoftheobjectsperson1.showAge()person2.showName()shouldoutput::23\nAnne -Arny JournalDev•November11,2019john’snameisnotfoundintheprogrambuttheoutputisthere.outputmismatchwithourprogram -muhi ThisworkislicensedunderaCreativeCommonsAttribution-NonCommercial-ShareAlike4.0InternationalLicense.TryDigitalOceanforfreeClickbelowtosignupandget$100ofcredittotryourproductsover60days!SignupPopularTopicsUbuntuLinuxBasicsJavaScriptReactPythonSecurityApacheMySQLDatabasesDockerKubernetesEbooksBrowsealltopictagsAlltutorialsQuestionsQ&AAskaquestionDigitalOceanProductDocsDigitalOceanSupportEventsTechTalksHacktoberfestDeployGetinvolvedCommunityNewsletterHollie'sHubforGoodWriteforDOnationsCommunitytoolsandintegrationsHatchStartupprogramJointheTechTalkSuccess!Thankyou!Pleasecheckyouremailforfurtherdetails.Pleasecompleteyourinformation!TutorialsQuestionsLearningPathsWriteforUsHacktoberfestToolsHomepagePricingProductOverviewMarketplaceControlPanelDocumentationContactSupportContactSalesSignin
延伸文章資訊
- 1Python class input argument - Stack Overflow
The init method is used to pass arguments to a class at creation. class Person(object): def __ini...
- 2Python Class Constructors: Control Your Object Instantiation
__init__() method. To this end, one of the most popular techniques is to use optional arguments. ...
- 3How 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...
- 4Methods - Python Like You Mean It
A class method is similar to an instance method, but it has a class object passed as its first ar...
- 5self in Python class - GeeksforGeeks
Self is the first argument to be passed in Constructor and Instance Method. Self must be provided...