Python Object Oriented Programming - Programiz
文章推薦指數: 80 %
The concept of OOP in Python focuses on creating reusable code. This concept is also known as DRY (Don't Repeat Yourself). In Python, the concept of OOP follows ... CourseIndex ExploreProgramiz Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnPythonpractically andGetCertified. ENROLL PopularTutorials GettingStartedWithPython PythonifStatement whileLoopinPython PythonLists DictionariesinPython StartLearningPython PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear ExplorePythonExamples ReferenceMaterials Built-inFunctions ListMethods DictionaryMethods StringMethods Viewall LearningPaths Challenges LearnPythonInteractively TryforFree Courses BecomeaPythonMaster BecomeaCMaster BecomeaJavaMaster ViewallCourses Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnPythonpractically andGetCertified. ENROLLFORFREE! PopularTutorials GettingStartedWithPython PythonifStatement whileLoopinPython PythonLists DictionariesinPython StartLearningPython AllPythonTutorials ReferenceMaterials Built-inFunctions ListMethods DictionaryMethods StringMethods Viewall Python JavaScript C C++ Java Kotlin LearnPythonpractically andGetCertified. ENROLLFORFREE! PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear AllPythonExamples LearnPythonInteractively PythonIntroduction GettingStarted KeywordsandIdentifier Statements&Comments PythonVariables PythonDataTypes PythonTypeConversion PythonI/OandImport PythonOperators PythonNamespace PythonFlowControl Pythonif...else PythonforLoop PythonwhileLoop Pythonbreakandcontinue PythonPass PythonFunctions PythonFunction FunctionArgument PythonRecursion AnonymousFunction Global,LocalandNonlocal PythonGlobalKeyword PythonModules PythonPackage PythonDatatypes PythonNumbers PythonList PythonTuple PythonString PythonSet PythonDictionary PythonFiles PythonFileOperation PythonDirectory PythonException ExceptionHandling User-definedException PythonObject&Class PythonOOP PythonClass PythonInheritance MultipleInheritance OperatorOverloading PythonAdvancedTopics PythonIterator PythonGenerator PythonClosure PythonDecorators PythonProperty PythonRegEx PythonExamples PythonDateandtime PythondatetimeModule Pythondatetime.strftime() Pythondatetime.strptime() Currentdate&time Getcurrenttime Timestamptodatetime PythontimeModule Pythontime.sleep() RelatedTopics PolymorphisminPython PythonObjectsandClasses PythonInheritance Pythonsuper() Pythonobject() PythonDocstrings PythonObjectOrientedProgramming Inthistutorial,you’lllearnaboutObject-OrientedProgramming(OOP)inPythonanditsfundamentalconceptwiththehelpofexamples. Video:Object-orientedProgramminginPython ObjectOrientedProgramming Pythonisamulti-paradigmprogramminglanguage.Itsupportsdifferentprogrammingapproaches. Oneofthepopularapproachestosolveaprogrammingproblemisbycreatingobjects.ThisisknownasObject-OrientedProgramming(OOP). Anobjecthastwocharacteristics: attributes behavior Let'stakeanexample: Aparrotisanobject,asithasthefollowingproperties: name,age,colorasattributes singing,dancingasbehavior TheconceptofOOPinPythonfocusesoncreatingreusablecode.ThisconceptisalsoknownasDRY(Don'tRepeatYourself). InPython,theconceptofOOPfollowssomebasicprinciples: Class Aclassisablueprintfortheobject. Wecanthinkofclassasasketchofaparrotwithlabels.Itcontainsallthedetailsaboutthename,colors,sizeetc.Basedonthesedescriptions,wecanstudyabouttheparrot.Here,aparrotisanobject. Theexampleforclassofparrotcanbe: classParrot: pass Here,weusetheclasskeywordtodefineanemptyclassParrot.Fromclass,weconstructinstances.Aninstanceisaspecificobjectcreatedfromaparticularclass. Object Anobject(instance)isaninstantiationofaclass.Whenclassisdefined,onlythedescriptionfortheobjectisdefined.Therefore,nomemoryorstorageisallocated. Theexampleforobjectofparrotclasscanbe: obj=Parrot() Here,objisanobjectofclassParrot. Supposewehavedetailsofparrots.Now,wearegoingtoshowhowtobuildtheclassandobjectsofparrots. Example1:CreatingClassandObjectinPython classParrot: #classattribute species="bird" #instanceattribute def__init__(self,name,age): self.name=name self.age=age #instantiatetheParrotclass blu=Parrot("Blu",10) woo=Parrot("Woo",15) #accesstheclassattributes print("Bluisa{}".format(blu.__class__.species)) print("Wooisalsoa{}".format(woo.__class__.species)) #accesstheinstanceattributes print("{}is{}yearsold".format(blu.name,blu.age)) print("{}is{}yearsold".format(woo.name,woo.age)) Output Bluisabird Wooisalsoabird Bluis10yearsold Woois15yearsold Intheaboveprogram,wecreatedaclasswiththenameParrot.Then,wedefineattributes.Theattributesareacharacteristicofanobject. Theseattributesaredefinedinsidethe__init__methodoftheclass.Itistheinitializermethodthatisfirstrunassoonastheobjectiscreated. Then,wecreateinstancesoftheParrotclass.Here,bluandwooarereferences(value)toournewobjects. Wecanaccesstheclassattributeusing__class__.species.Classattributesarethesameforallinstancesofaclass.Similarly,weaccesstheinstanceattributesusingblu.nameandblu.age.However,instanceattributesaredifferentforeveryinstanceofaclass. Tolearnmoreaboutclassesandobjects,gotoPythonClassesandObjects Methods Methodsarefunctionsdefinedinsidethebodyofaclass.Theyareusedtodefinethebehaviorsofanobject. Example2:CreatingMethodsinPython classParrot: #instanceattributes def__init__(self,name,age): self.name=name self.age=age #instancemethod defsing(self,song): return"{}sings{}".format(self.name,song) defdance(self): return"{}isnowdancing".format(self.name) #instantiatetheobject blu=Parrot("Blu",10) #callourinstancemethods print(blu.sing("'Happy'")) print(blu.dance()) Output Blusings'Happy' Bluisnowdancing Intheaboveprogram,wedefinetwomethodsi.esing()anddance().Thesearecalledinstancemethodsbecausetheyarecalledonaninstanceobjecti.eblu. Inheritance Inheritanceisawayofcreatinganewclassforusingdetailsofanexistingclasswithoutmodifyingit.Thenewlyformedclassisaderivedclass(orchildclass).Similarly,theexistingclassisabaseclass(orparentclass). Example3:UseofInheritanceinPython #parentclass classBird: def__init__(self): print("Birdisready") defwhoisThis(self): print("Bird") defswim(self): print("Swimfaster") #childclass classPenguin(Bird): def__init__(self): #callsuper()function super().__init__() print("Penguinisready") defwhoisThis(self): print("Penguin") defrun(self): print("Runfaster") peggy=Penguin() peggy.whoisThis() peggy.swim() peggy.run() Output Birdisready Penguinisready Penguin Swimfaster Runfaster Intheaboveprogram,wecreatedtwoclassesi.e.Bird(parentclass)andPenguin(childclass).Thechildclassinheritsthefunctionsofparentclass.Wecanseethisfromtheswim()method. Again,thechildclassmodifiedthebehavioroftheparentclass.WecanseethisfromthewhoisThis()method.Furthermore,weextendthefunctionsoftheparentclass,bycreatinganewrun()method. Additionally,weusethesuper()functioninsidethe__init__()method.Thisallowsustorunthe__init__()methodoftheparentclassinsidethechildclass. Encapsulation UsingOOPinPython,wecanrestrictaccesstomethodsandvariables.Thispreventsdatafromdirectmodificationwhichiscalledencapsulation.InPython,wedenoteprivateattributesusingunderscoreastheprefixi.esingle_ordouble__. Example4:DataEncapsulationinPython classComputer: def__init__(self): self.__maxprice=900 defsell(self): print("SellingPrice:{}".format(self.__maxprice)) defsetMaxPrice(self,price): self.__maxprice=price c=Computer() c.sell() #changetheprice c.__maxprice=1000 c.sell() #usingsetterfunction c.setMaxPrice(1000) c.sell() Output SellingPrice:900 SellingPrice:900 SellingPrice:1000 Intheaboveprogram,wedefinedaComputerclass. Weused__init__()methodtostorethemaximumsellingpriceofComputer.Here,noticethecode c.__maxprice=1000 Here,wehavetriedtomodifythevalueof__maxpriceoutsideoftheclass.However,since__maxpriceisaprivatevariable,thismodificationisnotseenontheoutput. Asshown,tochangethevalue,wehavetouseasetterfunctioni.esetMaxPrice()whichtakespriceasaparameter. Polymorphism Polymorphismisanability(inOOP)touseacommoninterfaceformultipleforms(datatypes). Suppose,weneedtocolorashape,therearemultipleshapeoptions(rectangle,square,circle).Howeverwecouldusethesamemethodtocoloranyshape.ThisconceptiscalledPolymorphism. Example5:UsingPolymorphisminPython classParrot: deffly(self): print("Parrotcanfly") defswim(self): print("Parrotcan'tswim") classPenguin: deffly(self): print("Penguincan'tfly") defswim(self): print("Penguincanswim") #commoninterface defflying_test(bird): bird.fly() #instantiateobjects blu=Parrot() peggy=Penguin() #passingtheobject flying_test(blu) flying_test(peggy) Output Parrotcanfly Penguincan'tfly Intheaboveprogram,wedefinedtwoclassesParrotandPenguin.Eachofthemhaveacommonfly()method.However,theirfunctionsaredifferent. Tousepolymorphism,wecreatedacommoninterfacei.eflying_test()functionthattakesanyobjectandcallstheobject'sfly()method.Thus,whenwepassedthebluandpeggyobjectsintheflying_test()function,itraneffectively. KeyPointstoRemember: Object-OrientedProgrammingmakestheprogrameasytounderstandaswellasefficient. Sincetheclassissharable,thecodecanbereused. Dataissafeandsecurewithdataabstraction. Polymorphismallowsthesameinterfacefordifferentobjects,soprogrammerscanwriteefficientcode. TableofContents IntroductiontoOOP inPython Class Object Methods Inheritance Encapsulation Polymorphism KeyPointstoRemember PreviousTutorial: User-definedException NextTutorial: PythonClass Shareon: Didyoufindthisarticlehelpful? Sorryaboutthat. Howcanweimproveit? Feedback* Leavethisfieldblank RelatedTutorialsPythonTutorialPolymorphisminPythonPythonTutorialPythonObjectsandClassesPythonTutorialPythonInheritancePythonLibraryPythonsuper() TryPROforFREE LearnPythonInteractively
延伸文章資訊
- 1【Python 教學】OOP 繼承/封裝/多型基本用法Example - 測試先生
- 2Python Object Oriented Programming - Programiz
The concept of OOP in Python focuses on creating reusable code. This concept is also known as DRY...
- 3給自己的Python小筆記: 物件導向設計OOP教學. 哈囉 - Chwang
給自己的Python小筆記: 物件導向設計OOP教學. 哈囉,今天來跟大家介紹一下物件導向設計OOP,相信大家學程式就算沒用到,也都一定會聽到OOP這個概念,在學習程式的過程 ...
- 42022 Python全攻略:OOP - HackMD
OOP is a method of structring a program by bounding related properties and behaviors into individ...
- 5Object-Oriented Programming (OOP) in Python 3
Object-oriented programming (OOP) is a method of structuring a program by bundling related proper...