Python Classes and Objects - DigitalOcean

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

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



請為這篇文章評分?