Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves...

33
Introduction to programming using Python Session 7 Matthieu Choplin [email protected] http://moodle.city.ac.uk/ 1

Transcript of Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves...

Page 2: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

ObjectivesTodescribeobjectsandclasses,anduseclassestomodelobjects.TodefineclassesToconstructanobjectusingaconstructorthatinvokestheinitializertocreateandinitializedatafieldsToaccessthemembersofobjectsusingthedotoperator(.)ToreferenceanobjectitselfwiththeselfparameterTouseUMLgraphicalnotationtodescribeclassesandobjectsTohidedatafieldstopreventdatacorruptionandmakeclasseseasytomaintainToapplyclassabstractionandencapsulationtosoftwaredevelopmentToexplorethedifferencesbetweentheproceduralparadigmandtheobjectorientedparadigm

2

Page 3: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

OOProgrammingConceptsObject-orientedprogramming(OOP)involvesprogrammingusingobjects.Anobjectrepresentsanentityintherealworldthatcanbedistinctlyidentified.Forexample,astudent,adesk,acircle,abutton,andevenaloancanallbeviewedasobjects.Anobjecthasauniqueidentity,state,andbehaviors.Thestateofanobjectconsistsofasetofdatafields(alsoknownasproperties)withtheircurrentvalues.Thebehaviorofanobjectisdefinedbyasetofmethods.

3

Page 4: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

Objects

Anobjecthasbothastateandbehavior.Thestatedefinestheobject,andthebehaviordefineswhattheobjectdoes.

4

Page 5: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

ClassesAPythonclassusesvariablestostoredatafieldsanddefinesmethodstoperformactions.Additionally,aclassprovidesaspecialtypemethod,knownasinitializer,whichisinvokedtocreateanewobject.Aninitializercanperformanyaction,butinitializerisdesignedtoperforminitialisingactions,suchascreatingthedatafieldsofobjects.

classClassName:#initializer#methods

5

Page 6: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

Exampleforcreatingaclassimportmath

classCircle:#Constructacircleobjectdef__init__(self,radius=1):self.radius=radius

defgetPerimeter(self):return2*self.radius*math.pi

defgetArea(self):returnself.radius*self.radius*math.pi

defsetRadius(self,radius):self.radius=radius

6

Page 7: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

Exampleforusingaclassandcreatingobjects

fromCircleimportCircle

defmain():#Createacirclewithradius1circle1=Circle()print("Theareaofthecircleofradius",circle1.radius,"is",circle1.getArea())

#Createacirclewithradius25circle2=Circle(25)print("Theareaofthecircleofradius",circle2.radius,"is",circle2.getArea())

#Createacirclewithradius125circle3=Circle(125)print("Theareaofthecircleofradius",circle3.radius,"is",circle3.getArea())

#Modifycircleradiuscircle2.radius=100print("Theareaofthecircleofradius",circle2.radius,"is",circle2.getArea())

main()#Callthemainfunction

7

Page 8: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

ConstructingObjectsOnceaclassisdefined,youcancreateobjectsfromtheclassbyusingthefollowingsyntax,calledaconstructor:

my_new_object=ClassName(optional_arguments)

8

Page 9: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

ConstructingObjectsTheeffectofconstructingaCircleobjectwith...

...isshownbelow:

my_new__circle_object=Circle(5)

9

Page 10: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

InstanceMethodsMethodsarefunctionsdefinedinsideaclass.Theyareinvokedbyobjectstoperformactionsontheobjects.Forthisreason,themethodsarealsocalledinstancemethodsinPython.Youprobablynoticedthatallthemethodsincludingtheconstructorhavethefirstparameterself,whichreferstotheobjectthatinvokesthemethod.Youcanuseanynameforthisparameter.Butbyconvention,selfisused.

10

Page 11: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

AccessingObjectsAfteranobjectiscreated,youcanaccessitsdatafieldsandinvokeitsmethodsusingthedotoperator(.),alsoknownastheobjectmemberaccessoperator.Forexample,thefollowingcodeaccessestheradiusdatafieldandinvokesthegetPerimeterandgetAreamethods.

[In1]fromCircleimportCircle[In2]c=Circle(5)[In3]c.getPerimeter()[Out3]31.41592653589793[In4]c.radius=10[In4]c.getArea()[Out4]314.1592653589793

11

Page 12: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

Whyself?Notethatthefirstparameterisspecial.Itisusedintheimplementationofthemethod,butnotusedwhenthemethodiscalled.So,whatisthisparameterselffor?WhydoesPythonneedit?selfisaparameterthatrepresentsanobject.Usingself,youcanaccessinstancevariablesinanobject.Instancevariablesareforstoringdatafields.Eachobjectisaninstanceofaclass.Instancevariablesaretiedtospecificobjects.Eachobjecthasitsowninstancevariables.Youcanusethesyntaxself.xtoaccesstheinstancevariablexfortheobjectselfinamethod.

12

Page 17: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

Exercise-TheRectangleclassFollowingtheexampleoftheCircleclass,designaclassnamedRectangletorepresentarectangle.Theclasscontains:

Twodatafieldsnamedwidthandheight.Aconstructorthatcreatesarectanglewiththespecifiedwidthandheight.Thedefaultvaluesare1and2forthewidthandheight,respectively.AmethodnamedgetArea()thatreturnstheareaofthisrectangleAmethodnamedgetPerimeter()thatreturnstheperimeter

DrawtheUMLdiagramfortheclass,andthenimplementtheclass.WriteatestprogramthatcreatestwoRectangleobjects—onewithwidth4andheight40andtheotherwithwidth3.5andheight35.7.Displaythewidth,height,area,andperimeterofeachrectangleinthisorder.

17

Page 18: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

DataFieldEncapsulationToprotectdata.Tomakeclasseseasytomaintain.Topreventdirectmodificationsofdatafields,don’tlettheclientdirectlyaccessdatafields.Thisisknownasdatafieldencapsulation.Thiscanbedonebydefiningprivatedatafields.InPython,theprivatedatafieldsaredefinedwithtwoleadingunderscores.Youcanalsodefineaprivatemethodnamedwithtwoleadingunderscores.

18

Page 19: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

Exampleformakingfieldsprivateimportmath

classCircle:#Constructacircleobjectdef__init__(self,radius=1):self.__radius=radius

defgetRadius(self):returnself.__radius

defgetPerimeter(self):return2*self.__radius*math.pi

defgetArea(self):returnself.__radius*self.__radius*math.pi

19

Page 20: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

DataFieldEncapsulation>>>fromCircleWithPrivateRadiusimportCircle>>>c=Circle(5)>>>c.__radiusAttributeError:'Circle'objecthasnoattribute'__radius'>>>c.getRadius()5

20

Page 21: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

DesignGuideIfaclassisdesignedforotherprogramstouse,topreventdatafrombeingtamperedwithandtomaketheclasseasytomaintain,definedatafieldsprivate.Ifaclassisonlyusedinternallybyyourownprogram,thereisnoneedtoencapsulatethedatafields.

21

Page 22: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

ClassAbstractionandEncapsulationClassabstractionmeanstoseparateclassimplementationfromtheuseoftheclass.Thecreatoroftheclassprovidesadescriptionoftheclassandlettheuserknowhowtheclasscanbeused.Theuseroftheclassdoesnotneedtoknowhowtheclassisimplemented.Thedetailofimplementationisencapsulatedandhiddenfromtheuser.

22

Page 23: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

TheLoanClassexampleAspecificloancanbeviewedasanobjectofaLoanclass.Theinterestrate,loanamount,andloanperiodareitsdataproperties,andcomputingmonthlypaymentandtotalpaymentareitsmethods.Whenyoubuyacar,aloanobjectiscreatedbyinstantiatingtheclasswithyourloaninterestrate,loanamount,andloanperiod.Youcanthenusethemethodstofindthemonthlypaymentandtotalpaymentofyourloan.AsauseroftheLoanclass,youdon’tneedtoknowhowthesemethodsareimplemented.

23

Page 26: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

Exercise-StockPriceDesignaclassnamedStocktorepresentacompany’sstockthatcontains:

Aprivatestringdatafieldnamedsymbolforthestock’ssymbol.Aprivatestringdatafieldnamednameforthestock’sname.AprivatefloatdatafieldnamedpreviousClosingPricethatstoresthestockpriceforthepreviousdayAprivatefloatdatafieldnamedcurrentPricethatstoresthestockpriceforthecurrenttime.Aconstructorthatcreatesastockwiththespecifiedsymbol,name,previousprice,andcurrentpriceAgetmethodforreturningthestocknameAgetmethodforreturningthestocksymbolGetandsetmethodsforgetting/settingthestock’spreviousprice.Getandsetmethodsforgetting/settingthestock’scurrentprice.AmethodnamedgetChangePercent()thatreturnsthepercentagechangedfrompreviousClosingPricetocurrentPrice

DrawtheUMLdiagramfortheclass,andthenimplementtheclass.WriteatestprogramthatcreatesaStockobjectwiththestocksymbolINTC,thenameIntelCorporation,thepreviousclosingpriceof20.5,andthenewcurrentpriceof20.35,anddisplaytheprice changepercentage.

26

Page 27: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

SeethedifferencebetweenproceduralandOOthinking

WriteaprogramthatpromptstheusertoenteraweightinpoundsandheightininchesandthendisplaystheBMI.Notethatonepoundis0.45359237kilogramsandoneinchis0.0254meters.

Seetheprogram

Butwecouldalsowritethisprogramusingclasses

BMI_procedural.py

27

Page 30: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

Proceduralvs.Object-Oriented(1)Inproceduralprogramming,dataandoperationsonthedataareseparate,andthismethodologyrequiressendingdatatomethods.Object-orientedprogrammingplacesdataandtheoperationsthatpertaintotheminanobject.Thisapproachsolvesmanyoftheproblemsinherentinproceduralprogramming.

30

Page 31: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

Proceduralvs.Object-Oriented(2)Theobject-orientedprogrammingapproachorganizesprogramsinawaythatmirrorstherealworld,inwhichallobjectsareassociatedwithbothattributesandactivities.Usingobjectsimprovessoftwarereusabilityandmakesprogramseasiertodevelopandeasiertomaintain.ProgramminginPythoninvolvesthinkingintermsofobjects;aPythonprogramcanbeviewedasacollectionofcooperatingobjects.

31

Page 32: Session 7 - mattchoplin.com · OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that

Exercise-StopwatchDesignaclassnamedStopWatch.Theclasscontains:

TheprivatedatafieldsstartTimeandendTimewithgetmethods.AconstructorthatinitializesstartTimewiththecurrenttime.Amethodnamedstart()thatresetsthestartTimetothecurrenttime.Amethodnamedstop()thatsetstheendTimetothecurrenttime.AmethodnamedgetElapsedTime()thatreturnstheelapsedtimeforthestopwatchinmilliseconds.

DrawtheUMLdiagramfortheclass,andthenimplementtheclass.Writeatestprogramthatmeasurestheexecutiontimeofaddingnumbersfrom1to1,000,000.

32