session 7 - mattchoplin.com · oo programming concepts object-oriented programming (oop) involves...
TRANSCRIPT
IntroductiontoprogrammingusingPython
Session7MatthieuChoplin
http://moodle.city.ac.uk/
1
ObjectivesTodescribeobjectsandclasses,anduseclassestomodelobjects.TodefineclassesToconstructanobjectusingaconstructorthatinvokestheinitializertocreateandinitializedatafieldsToaccessthemembersofobjectsusingthedotoperator(.)ToreferenceanobjectitselfwiththeselfparameterTouseUMLgraphicalnotationtodescribeclassesandobjectsTohidedatafieldstopreventdatacorruptionandmakeclasseseasytomaintainToapplyclassabstractionandencapsulationtosoftwaredevelopmentToexplorethedifferencesbetweentheproceduralparadigmandtheobjectorientedparadigm
2
OOProgrammingConceptsObject-orientedprogramming(OOP)involvesprogrammingusingobjects.Anobjectrepresentsanentityintherealworldthatcanbedistinctlyidentified.Forexample,astudent,adesk,acircle,abutton,andevenaloancanallbeviewedasobjects.Anobjecthasauniqueidentity,state,andbehaviors.Thestateofanobjectconsistsofasetofdatafields(alsoknownasproperties)withtheircurrentvalues.Thebehaviorofanobjectisdefinedbyasetofmethods.
3
Objects
Anobjecthasbothastateandbehavior.Thestatedefinestheobject,andthebehaviordefineswhattheobjectdoes.
4
ClassesAPythonclassusesvariablestostoredatafieldsanddefinesmethodstoperformactions.Additionally,aclassprovidesaspecialtypemethod,knownasinitializer,whichisinvokedtocreateanewobject.Aninitializercanperformanyaction,butinitializerisdesignedtoperforminitialisingactions,suchascreatingthedatafieldsofobjects.
classClassName:#initializer#methods
5
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
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
ConstructingObjectsOnceaclassisdefined,youcancreateobjectsfromtheclassbyusingthefollowingsyntax,calledaconstructor:
my_new_object=ClassName(optional_arguments)
8
ConstructingObjectsTheeffectofconstructingaCircleobjectwith...
...isshownbelow:
my_new__circle_object=Circle(5)
9
InstanceMethodsMethodsarefunctionsdefinedinsideaclass.Theyareinvokedbyobjectstoperformactionsontheobjects.Forthisreason,themethodsarealsocalledinstancemethodsinPython.Youprobablynoticedthatallthemethodsincludingtheconstructorhavethefirstparameterself,whichreferstotheobjectthatinvokesthemethod.Youcanuseanynameforthisparameter.Butbyconvention,selfisused.
10
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
Whyself?Notethatthefirstparameterisspecial.Itisusedintheimplementationofthemethod,butnotusedwhenthemethodiscalled.So,whatisthisparameterselffor?WhydoesPythonneedit?selfisaparameterthatrepresentsanobject.Usingself,youcanaccessinstancevariablesinanobject.Instancevariablesareforstoringdatafields.Eachobjectisaninstanceofaclass.Instancevariablesaretiedtospecificobjects.Eachobjecthasitsowninstancevariables.Youcanusethesyntaxself.xtoaccesstheinstancevariablexfortheobjectselfinamethod.
12
UMLClassDiagram
13
Example:DefiningClassesandCreatingObjects
14
Example:DefiningClassesandCreatingObjectsSeeSee
TV.pyTestTV.py
15
TraceexecutionSeewhatishappeninginmemorywith (clicklink)
Pythontutor
16
Exercise-TheRectangleclassFollowingtheexampleoftheCircleclass,designaclassnamedRectangletorepresentarectangle.Theclasscontains:
Twodatafieldsnamedwidthandheight.Aconstructorthatcreatesarectanglewiththespecifiedwidthandheight.Thedefaultvaluesare1and2forthewidthandheight,respectively.AmethodnamedgetArea()thatreturnstheareaofthisrectangleAmethodnamedgetPerimeter()thatreturnstheperimeter
DrawtheUMLdiagramfortheclass,andthenimplementtheclass.WriteatestprogramthatcreatestwoRectangleobjects—onewithwidth4andheight40andtheotherwithwidth3.5andheight35.7.Displaythewidth,height,area,andperimeterofeachrectangleinthisorder.
17
DataFieldEncapsulationToprotectdata.Tomakeclasseseasytomaintain.Topreventdirectmodificationsofdatafields,don’tlettheclientdirectlyaccessdatafields.Thisisknownasdatafieldencapsulation.Thiscanbedonebydefiningprivatedatafields.InPython,theprivatedatafieldsaredefinedwithtwoleadingunderscores.Youcanalsodefineaprivatemethodnamedwithtwoleadingunderscores.
18
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
DataFieldEncapsulation>>>fromCircleWithPrivateRadiusimportCircle>>>c=Circle(5)>>>c.__radiusAttributeError:'Circle'objecthasnoattribute'__radius'>>>c.getRadius()5
20
DesignGuideIfaclassisdesignedforotherprogramstouse,topreventdatafrombeingtamperedwithandtomaketheclasseasytomaintain,definedatafieldsprivate.Ifaclassisonlyusedinternallybyyourownprogram,thereisnoneedtoencapsulatethedatafields.
21
ClassAbstractionandEncapsulationClassabstractionmeanstoseparateclassimplementationfromtheuseoftheclass.Thecreatoroftheclassprovidesadescriptionoftheclassandlettheuserknowhowtheclasscanbeused.Theuseroftheclassdoesnotneedtoknowhowtheclassisimplemented.Thedetailofimplementationisencapsulatedandhiddenfromtheuser.
22
TheLoanClassexampleAspecificloancanbeviewedasanobjectofaLoanclass.Theinterestrate,loanamount,andloanperiodareitsdataproperties,andcomputingmonthlypaymentandtotalpaymentareitsmethods.Whenyoubuyacar,aloanobjectiscreatedbyinstantiatingtheclasswithyourloaninterestrate,loanamount,andloanperiod.Youcanthenusethemethodstofindthemonthlypaymentandtotalpaymentofyourloan.AsauseroftheLoanclass,youdon’tneedtoknowhowthesemethodsareimplemented.
23
DesigningtheLoanClass
24
SeetheprogramSeetheprogram
Loan.pyTestLoanClass.py
25
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
SeethedifferencebetweenproceduralandOOthinking
WriteaprogramthatpromptstheusertoenteraweightinpoundsandheightininchesandthendisplaystheBMI.Notethatonepoundis0.45359237kilogramsandoneinchis0.0254meters.
Seetheprogram
Butwecouldalsowritethisprogramusingclasses
BMI_procedural.py
27
TheBMIClass
28
TheBMIClassSeetheprogramSeetheprogram
BMI.pyUseBMIClass.py
29
Proceduralvs.Object-Oriented(1)Inproceduralprogramming,dataandoperationsonthedataareseparate,andthismethodologyrequiressendingdatatomethods.Object-orientedprogrammingplacesdataandtheoperationsthatpertaintotheminanobject.Thisapproachsolvesmanyoftheproblemsinherentinproceduralprogramming.
30
Proceduralvs.Object-Oriented(2)Theobject-orientedprogrammingapproachorganizesprogramsinawaythatmirrorstherealworld,inwhichallobjectsareassociatedwithbothattributesandactivities.Usingobjectsimprovessoftwarereusabilityandmakesprogramseasiertodevelopandeasiertomaintain.ProgramminginPythoninvolvesthinkingintermsofobjects;aPythonprogramcanbeviewedasacollectionofcooperatingobjects.
31
Exercise-StopwatchDesignaclassnamedStopWatch.Theclasscontains:
TheprivatedatafieldsstartTimeandendTimewithgetmethods.AconstructorthatinitializesstartTimewiththecurrenttime.Amethodnamedstart()thatresetsthestartTimetothecurrenttime.Amethodnamedstop()thatsetstheendTimetothecurrenttime.AmethodnamedgetElapsedTime()thatreturnstheelapsedtimeforthestopwatchinmilliseconds.
DrawtheUMLdiagramfortheclass,andthenimplementtheclass.Writeatestprogramthatmeasurestheexecutiontimeofaddingnumbersfrom1to1,000,000.
32
Solutionrectangle.pystock.pystopwatch.py
33