OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make...
Transcript of OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make...
OOPprinciples(again)
• encapsulation:hidingdesigndetailstomaketheprogramclearerandmoreeasilymodifiedlater
• modularity:theabilitytomakeobjects“standalone”sotheycanbereused(ourmodules).Likethemathmodule
• inheritance:createanewobjectbyinheriting(likefathertoson)manyobjectcharacteristicswhilecreatingorover-ridingforthisobject
• polymorphism:(hard)Allowonemessagetobesenttoanyobjectandhaveitrespondappropriatelybasedonthetypeofobjectitis.
Therearenowthreegroupsinourcodingscheme:userprogrammer,classuserprogrammer,classdesigner
• Theclassdesigneriscreatingcodetobeusedbyotherprogrammers
• Insodoing,theclassdesignerismakingakindoflibrarythatotherprogrammerscantakeadvantageof
encapsulation
• Hidingthedetailsofwhatthemessageentailsmeansthatchangescanbemadetotheobjectandtheflowofmessages(andtheirresults)canstaythesame
• Thustheimplementationofthemessagecanchangebutitsintendedeffectstaythesame
• Iftheclassiswelldesigned,thenauseroftheclassneedonlyusetheprovidedmethodstousetheclassinstance.
• Theclassdesignerisfreetoplaceinformationintheclassthatisimportanttothedesigner,butnottheuser,oftheclass.
• Theclassdesignerhidesdetailsoftheimplementationsothattheprogramwaseasiertoreadandwrite
• modularity,makeanobjectsothatitcanbereusedinothercontexts
• providinganinterface(themethods)thataretheapprovedwaytodealwiththeclassHidesdetailsoftheimplementationsothattheprogramwaseasiertoreadandwrite
• Providesmodularitythatmakesanobjectsothatitcanbereusedinothercontexts
Inheritance
• Inheritanceallowstheclassdesignertoutilizethedesignofanexistingclasstocreateanewclass.
• Thatis,wecancreateanewclassthatspecializesanexistingclassbyutilizingtheexistingclass’sattributes,specializingonlythoseattributesthatdistinguishthenewclass.
• Inthisway,classescansharecommonelementsandchangeonlythoseattributesthatdistinguishthenewclass.
Class-Instancerelations
• Remembertherelationshipbetweenaclassanditsinstances– aclasscanhavemanyinstances,eachmadeinitiallyfromtheconstructoroftheclass
– themethodsthataninstancecancallareinitiallysharedbyallinstancesofaclass
– Whenreferencingavalueinanattribute,Pythonfirstlooksintheinstancefortheattribute,and,ifnotfoundthere,itthenlooksintheclasstheinstancewasderivedfrom.Inthisway,attributesstoredintheclassareavailabletoeveryinstancederivedfromtheclass.
Class-Classrelations• Classescanalsohaveaseparaterelationshipwithotherclasses• therelationshipsformsahierarchy– hierarchy:Abodyofpersonsorthingsrankedingrades,ordersorclasses,oneaboveanother
• whenwecreateaclass,whichisitselfanotherobject,wecanstatehowitisrelatedtootherclasses
• therelationshipwecanindicateistheclassthatis'above'itinthehierarchy
• Everyclassmaintainsatleastoneparentclass.
Classesrelatedbyahierarchy
classstatement
class MyClass (SuperClass): pass
• ThetopclassinPythoniscalledobject.• itispredefinedbyPython,alwaysexists• useobjectwhenyouhavenosuperclass
nameoftheclassabovethisclassinthehierarchy
• Theis-arelationshipisoneway,muchastheinstance-ofrelationship.
• Theinstancerememberwhoitsclassis,buttheclassdoesnottrackitsinstance.
• Aclassrememberwhoitsparentclassis,buttheparentclassdoesnottrackitschildclasses.
SubclassExample•Polygon -objectwithnunequalsides•Regularpolygon:specialPolygon -objectwithnsides,allequallength•Triangle:specialpolygon(3sides)•Square:specialregularpolygon
ClassHierarchy•classPolygon:•classregPolygon(Polygon):•classTriangle(Polygon):•classSquare(regPolygon):•classequiTriangle(Triangle)orclassequiTriangle(regPolygon)
• EachPythonclassindicatesspecificallyinitsclassdefinitionwhoitsparentis.
• Thisrelationshipisrecordedinthe__bases__attributeofeachclass.
is-a,superandsubclass
• theclasshierarchyimposesanis-arelationshipbetweenclasses– MyChildClassis-a(orisakindof)MyClass– MyClassis-a(orisakindof)object
• Anexample:ifyoucreateaCarclass,thenaFordclassisaCar,butamoreparticularkindofCar.Subsequently,aMustangclassisaFordclass,butamoreparticularkindofFord.
• thehopeofsuchanarrangementisthesaving/re-useofcode.Ifanewclassiscreatedaspartofanexistingclasshierarchy,thenthenewclasscanreuseexistingcodefromthehierarchy,specializingonlythoseaspectsorattributesthatareuniquetothenewclass.
• superclasscodecontainsgeneralcodethatisapplicabletomanysubclasses.Bysharingcodefromtheclasshierarchy,thecodingofclassescanbesomewhatstandardized.
• subclassusessuperclasscode(viasharing)butspecializescodeforitselfwhennecessary
Scopeforobjects,thefullstory
1. Lookintheobjectfortheattribute2. Ifnotintheobject,looktotheobject'sclassforthe
attribute(uptheinstance-ofcreation)3. Ifnotintheobject'sclass,lookupthehierarchyof
thatclassfortheattribute(uptheis-arelation)4. Ifyouhitobject,thentheattributedoesnotexist
builtinsareobjectstoo
• Oneniceway,easyway,touseinheritanceistonotethatallthebuiltintypesareobjectsalso
• thusyoucaninheritthepropertiesofbuiltintypesthenmodifyhowtheygetusedinyoursubclass
• youcanalsouseanyofthetypesyoupullinasmodules
specializingamethod
• Onetechnicaldetail.Normalmethodcallsarecalledboundmethods.Boundmethodshaveaninstanceinfrontofthemethodcallandautomaticallypassself
my_inst = MyClass() my_inst.method(arg1,arg2)
• my_instisaninstance,sothemethodisbound
unboundmethods
itisalsopossibletocallamethodwithoutPythonbindingself.Inthatcase,theuserhastodoit.• unboundmethodsarecalledaspartoftheclassbutselfpassedbytheuser
my_inst = MyClass() MyClass.method(my_inst, arg2, arg3)
selfispassedexplicitly(my_inst here)!
• Consideranexample.Wewanttospecializeanewclassasasubclassoflist.
class MyClass(list):
• easyenough,butwewanttomakesurethatwegetournewclassinstancesinitializedthewaytheyaresupposedto,bycalling__init__ ofthesuperclass
Whycallthesuperclassinit?
Ifwedon'texplicitlysayso,ourclassmayinheritstufffromthesuperclass,butwemustmakesurewecallitinthepropercontext.Forexample,our__init__wouldbe:def __init__(self): list.__init__(self)# do anything else special to MyClass
explicitcallstothesuper
• weexplicitlycallthesuperclassconstructorusinganunboundmethod
• then,afteritcompleteswecandoanythingspecialforournewclass
• Wespecializethenewclassbutinheritmostoftheworkfromthesuper.
Givesusawaytoorganizecode
• specialization.Asubclasscaninheritcodefromitssuperclass,butmodifyanythingthatisparticulartothatsubclass
• over-ride.changeabehaviortobespecifictoasubclass
• reuse-code.Usecodefromotherclasses(withoutrewriting)togetbehaviorinourclass.
Specialclassmethods
Whataremagicmethods?They'reeverythinginobject-orientedPython.They'respecialmethodsthatyoucandefinetoadd"magic"toyourclasses.They'realwayssurroundedbydoubleunderscores(e.g.__init__or__lt__).
Aclasscanimplementcertainoperationsthatareinvokedbyspecialsyntax(suchasarithmeticoperationsorsubscriptingandslicing)bydefiningmethodswithspecialnames.ThisisPython’sapproachtooperatoroverloading,allowingclassestodefinetheirownbehaviorwithrespecttolanguageoperators.
Enhancesclasseswithfeaturessuchasslices,item,callingcapability,mathematicaloperationsetc.
ClassSpecialMethods•__init__•__call__•__item__•__add__•__slice__•__repr__•__str__•__hash__•__len__•__getattr__•__setattr__•__delattr__•__delete__•__getitem__•__setitem__•__delitem__•__iter__
•__reversed__•__contains__•__getslice__•__delslice__•__add__•__sub__•__mod__•__divmod__•__pow__•__and__•__xor__•__or__•__neg__•__pos__•__abs__•__int__•__float__
•__lt__•__le__•__eq__•__ne__•__gt__•__ge__•manymore
Operatoroverloading• theplusoperatorisoverloaded
• thatis,theoperatorcando/meandifferentthings(havemultiple/overloadedmeanings)dependingonthetypesinvolved
• ifpythondoesnotrecognizetheoperationandthatcombinationoftypes,yougetanerror
Whatdoesvar1+var2 do?• withtwostrings,wegetconcatenation• withtwointegers,wegetaddition• withanintegerandastringweget:Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> 1+'a' TypeError: unsupported operand type(s) for +: 'int' and 'str'
Pythonoverloadops• Pythonprovidesasetofoperatorsthatcanbeoverloaded.You
can'toverloadalltheoperators,butyoucanformany
• Likeallthespecialclassoperations,theyusethetwounderlinesbeforeandafter.
• Theycomeinthreegeneralclasses:– numerictypeoperations(+,-,<,>,printetc.)– containeroperations([],iterate,len,etc.)– generaloperations(printing,construction)
howdoesv1+v2mapto__add__v1 + v2
isturned,byPython,into
v1.__add__(v2)
• Theseareexactlyequivalentexpressions.Itmeansthatthefirstvariablecallsthe__add__methodwiththesecondvariablepassedasanargument
v1isboundtoself,v2boundtoparam2
Example:-creationofaspecializedvectorclassthatsupportsaddition,subtraction,etc.
- vectorshouldbeabletoholdanytypethatsupportsaddition,subtraction,etc.
Additionsoflistsa=[1,2,'string']b=[1,3,'cat']
Output[1,2,'string',1,3,'cat']
Desiredoutput[2,5,'stringcat']
Using__setitem__and__getitem__forthisexample.
object.__setitem__(self,key,value)Calledtoimplementassignmenttoself[key].Samenoteasfor__getitem__().Thisshouldonlybeimplementedformappingsiftheobjectssupportchangestothevaluesforkeys,orifnewkeys can be added, or for sequences if elements can bereplaced.Thesameexceptionsshouldberaisedfor improperkeyvaluesasforthe__getitem__()method.
Betterapproaches
•Insteadofcreatinganewclass,takeadvantageofexistingclasses
•Twopossibilities -subclassthelistclass -extendlist notreallypossiblebecauselistisbuilt-in
SubclassListclass
Extendauserclass
Ifyourunitagain:
Callableobjects•Insideaclass,defineamethod__call__•Theinstanceofaclasscannowbeusedasafunction
classnamespacesaredicts• thenamespacesineveryobjectandmoduleisindeedanamespace• thatdictionaryisboundtothespecialvariable__dict__• itlistsallthelocalattributes(variables,functions)intheobject• AlmosteverythinginPythonworksthroughdictionaries• Classattributes(variables)arestoredinadictionaryassociatedwith
theclass• •The__dict__dictionaryisnotsharedbetweenAttributes
• Example:•Dogdog dog.weightisequivalentto dog.__dict__[‘weight’]
Dictionaries ClassandClassinstanceshaveseparatedictionaries
Dogdict:{'__module__':'__main__','pprint':<functionpprintat0x10a472ed8>,'__doc__':None,'__init__':<function__init__at0x10a472aa0>}dogdict:{'color':'blue','name':'punk','weight':'100lb'}
ClassforScientificComputing
Inlinelambdafunctions• Pythonoffersanonymousinlinefunctionsknownaslambda
function.• Theconstructionis“lambda<args>:<expression>”
• Itisequivalenttoafunctionwith<args>asargumentsand<expression>asreturnvalue:
defsomefunc(<args>):return<expression>
• Forexample,“lambdax,y,z:3*x+2*y-z”isashortcutfordefsomefunc(x,y,z)return3*x+2*y–z
Inlinelambdafunctions• Lambdafunctioncanbeusedinplacewhereweexpectvariables.
• Saywehaveafunctiontakinganotherfunctionasargument:
deffill(a,f)n=len(a);dx=1.0/(n-1)foriinrange(n):x=i*dx a[i]=f(x)• Alambdafunctioncanbeusedforthefargument:fill(a,lambdax:<expression>)
OOPforIntegrationConsiderotherquadraturerules:• Simpson’srule
• Two-pointGauss-Legendrerule
1
1
1 4 1( ) ( 1) (0) (1)3 3 3
f x dx f f f−
≈ − + +∫
1
1
1 1( ) ( ) ( )3 3
f x dx f f−
≈ − +∫
WriteaPythonclassTrapezoidaltoevaluatenumericalintegrationusingthetrapezoidalrule.
1
1( ) ( 1) (1)f x dx f f
−≈ − +∫
Itisoneofthequadraturerulesthatcanbeexpressedinthegeneralform:
1
11
( ) ( )n
i ii
f x dx w f x−
=
≈∑∫Usetheclasstocompute
1 3
1x dx
−∫