OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make...

46
OOP principles (again) encapsulation: hiding design details to make the program clearer and more easily modified later modularity: the ability to make objects “stand alone” so they can be reused (our modules). Like the math module inheritance: create a new object by inheriting (like father to son) many object characteristics while creating or over-riding for this object polymorphism: (hard) Allow one message to be sent to any object and have it respond appropriately based on the type of object it is.

Transcript of OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make...

Page 1: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

OOPprinciples(again)

• encapsulation:hidingdesigndetailstomaketheprogramclearerandmoreeasilymodifiedlater

• modularity:theabilitytomakeobjects“standalone”sotheycanbereused(ourmodules).Likethemathmodule

• inheritance:createanewobjectbyinheriting(likefathertoson)manyobjectcharacteristicswhilecreatingorover-ridingforthisobject

• polymorphism:(hard)Allowonemessagetobesenttoanyobjectandhaveitrespondappropriatelybasedonthetypeofobjectitis.

Page 2: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

Therearenowthreegroupsinourcodingscheme:userprogrammer,classuserprogrammer,classdesigner

• Theclassdesigneriscreatingcodetobeusedbyotherprogrammers

• Insodoing,theclassdesignerismakingakindoflibrarythatotherprogrammerscantakeadvantageof

Page 3: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

encapsulation

• Hidingthedetailsofwhatthemessageentailsmeansthatchangescanbemadetotheobjectandtheflowofmessages(andtheirresults)canstaythesame

• Thustheimplementationofthemessagecanchangebutitsintendedeffectstaythesame

• Iftheclassiswelldesigned,thenauseroftheclassneedonlyusetheprovidedmethodstousetheclassinstance.

• Theclassdesignerisfreetoplaceinformationintheclassthatisimportanttothedesigner,butnottheuser,oftheclass.

• Theclassdesignerhidesdetailsoftheimplementationsothattheprogramwaseasiertoreadandwrite

Page 4: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

• modularity,makeanobjectsothatitcanbereusedinothercontexts

• providinganinterface(themethods)thataretheapprovedwaytodealwiththeclassHidesdetailsoftheimplementationsothattheprogramwaseasiertoreadandwrite

• Providesmodularitythatmakesanobjectsothatitcanbereusedinothercontexts

Page 5: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

Inheritance

• Inheritanceallowstheclassdesignertoutilizethedesignofanexistingclasstocreateanewclass.

• Thatis,wecancreateanewclassthatspecializesanexistingclassbyutilizingtheexistingclass’sattributes,specializingonlythoseattributesthatdistinguishthenewclass.

• Inthisway,classescansharecommonelementsandchangeonlythoseattributesthatdistinguishthenewclass.

Page 6: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

Class-Instancerelations

• Remembertherelationshipbetweenaclassanditsinstances– aclasscanhavemanyinstances,eachmadeinitiallyfromtheconstructoroftheclass

– themethodsthataninstancecancallareinitiallysharedbyallinstancesofaclass

– Whenreferencingavalueinanattribute,Pythonfirstlooksintheinstancefortheattribute,and,ifnotfoundthere,itthenlooksintheclasstheinstancewasderivedfrom.Inthisway,attributesstoredintheclassareavailabletoeveryinstancederivedfromtheclass.

Page 7: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

Class-Classrelations• Classescanalsohaveaseparaterelationshipwithotherclasses• therelationshipsformsahierarchy– hierarchy:Abodyofpersonsorthingsrankedingrades,ordersorclasses,oneaboveanother

• whenwecreateaclass,whichisitselfanotherobject,wecanstatehowitisrelatedtootherclasses

• therelationshipwecanindicateistheclassthatis'above'itinthehierarchy

• Everyclassmaintainsatleastoneparentclass.

Classesrelatedbyahierarchy

Page 8: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

classstatement

class MyClass (SuperClass): pass

• ThetopclassinPythoniscalledobject.• itispredefinedbyPython,alwaysexists• useobjectwhenyouhavenosuperclass

nameoftheclassabovethisclassinthehierarchy

Page 9: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

• Theis-arelationshipisoneway,muchastheinstance-ofrelationship.

• Theinstancerememberwhoitsclassis,buttheclassdoesnottrackitsinstance.

• Aclassrememberwhoitsparentclassis,buttheparentclassdoesnottrackitschildclasses.

Page 10: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

SubclassExample•Polygon -objectwithnunequalsides•Regularpolygon:specialPolygon -objectwithnsides,allequallength•Triangle:specialpolygon(3sides)•Square:specialregularpolygon

ClassHierarchy•classPolygon:•classregPolygon(Polygon):•classTriangle(Polygon):•classSquare(regPolygon):•classequiTriangle(Triangle)orclassequiTriangle(regPolygon)

Page 11: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

• EachPythonclassindicatesspecificallyinitsclassdefinitionwhoitsparentis.

• Thisrelationshipisrecordedinthe__bases__attributeofeachclass.

Page 12: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

is-a,superandsubclass

• theclasshierarchyimposesanis-arelationshipbetweenclasses– MyChildClassis-a(orisakindof)MyClass– MyClassis-a(orisakindof)object

• Anexample:ifyoucreateaCarclass,thenaFordclassisaCar,butamoreparticularkindofCar.Subsequently,aMustangclassisaFordclass,butamoreparticularkindofFord.

Page 13: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

• thehopeofsuchanarrangementisthesaving/re-useofcode.Ifanewclassiscreatedaspartofanexistingclasshierarchy,thenthenewclasscanreuseexistingcodefromthehierarchy,specializingonlythoseaspectsorattributesthatareuniquetothenewclass.

• superclasscodecontainsgeneralcodethatisapplicabletomanysubclasses.Bysharingcodefromtheclasshierarchy,thecodingofclassescanbesomewhatstandardized.

• subclassusessuperclasscode(viasharing)butspecializescodeforitselfwhennecessary

Page 14: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

Scopeforobjects,thefullstory

1. Lookintheobjectfortheattribute2. Ifnotintheobject,looktotheobject'sclassforthe

attribute(uptheinstance-ofcreation)3. Ifnotintheobject'sclass,lookupthehierarchyof

thatclassfortheattribute(uptheis-arelation)4. Ifyouhitobject,thentheattributedoesnotexist

Page 15: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to
Page 16: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

builtinsareobjectstoo

• Oneniceway,easyway,touseinheritanceistonotethatallthebuiltintypesareobjectsalso

• thusyoucaninheritthepropertiesofbuiltintypesthenmodifyhowtheygetusedinyoursubclass

• youcanalsouseanyofthetypesyoupullinasmodules

Page 17: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

specializingamethod

• Onetechnicaldetail.Normalmethodcallsarecalledboundmethods.Boundmethodshaveaninstanceinfrontofthemethodcallandautomaticallypassself

my_inst = MyClass() my_inst.method(arg1,arg2)

• my_instisaninstance,sothemethodisbound

Page 18: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

unboundmethods

itisalsopossibletocallamethodwithoutPythonbindingself.Inthatcase,theuserhastodoit.• unboundmethodsarecalledaspartoftheclassbutselfpassedbytheuser

my_inst = MyClass() MyClass.method(my_inst, arg2, arg3)

selfispassedexplicitly(my_inst here)!

Page 19: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

• Consideranexample.Wewanttospecializeanewclassasasubclassoflist.

class MyClass(list):

• easyenough,butwewanttomakesurethatwegetournewclassinstancesinitializedthewaytheyaresupposedto,bycalling__init__ ofthesuperclass

Page 20: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

Whycallthesuperclassinit?

Ifwedon'texplicitlysayso,ourclassmayinheritstufffromthesuperclass,butwemustmakesurewecallitinthepropercontext.Forexample,our__init__wouldbe:def __init__(self): list.__init__(self)# do anything else special to MyClass

Page 21: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

explicitcallstothesuper

• weexplicitlycallthesuperclassconstructorusinganunboundmethod

• then,afteritcompleteswecandoanythingspecialforournewclass

• Wespecializethenewclassbutinheritmostoftheworkfromthesuper.

Page 22: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

Givesusawaytoorganizecode

• specialization.Asubclasscaninheritcodefromitssuperclass,butmodifyanythingthatisparticulartothatsubclass

• over-ride.changeabehaviortobespecifictoasubclass

• reuse-code.Usecodefromotherclasses(withoutrewriting)togetbehaviorinourclass.

Page 23: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

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.

Page 24: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

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

Page 25: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to
Page 26: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

Operatoroverloading• theplusoperatorisoverloaded

• thatis,theoperatorcando/meandifferentthings(havemultiple/overloadedmeanings)dependingonthetypesinvolved

• ifpythondoesnotrecognizetheoperationandthatcombinationoftypes,yougetanerror

Page 27: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

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'

Page 28: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

Pythonoverloadops• Pythonprovidesasetofoperatorsthatcanbeoverloaded.You

can'toverloadalltheoperators,butyoucanformany

• Likeallthespecialclassoperations,theyusethetwounderlinesbeforeandafter.

• Theycomeinthreegeneralclasses:– numerictypeoperations(+,-,<,>,printetc.)– containeroperations([],iterate,len,etc.)– generaloperations(printing,construction)

Page 29: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

howdoesv1+v2mapto__add__v1 + v2

isturned,byPython,into

v1.__add__(v2)

• Theseareexactlyequivalentexpressions.Itmeansthatthefirstvariablecallsthe__add__methodwiththesecondvariablepassedasanargument

v1isboundtoself,v2boundtoparam2

Page 30: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

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']

Page 31: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

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.

Page 32: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to
Page 33: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to
Page 34: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

Betterapproaches

•Insteadofcreatinganewclass,takeadvantageofexistingclasses

•Twopossibilities -subclassthelistclass -extendlist notreallypossiblebecauselistisbuilt-in

Page 35: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

SubclassListclass

Page 36: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

Extendauserclass

Ifyourunitagain:

Page 37: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

Callableobjects•Insideaclass,defineamethod__call__•Theinstanceofaclasscannowbeusedasafunction

Page 38: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

classnamespacesaredicts• thenamespacesineveryobjectandmoduleisindeedanamespace• thatdictionaryisboundtothespecialvariable__dict__• itlistsallthelocalattributes(variables,functions)intheobject• AlmosteverythinginPythonworksthroughdictionaries• Classattributes(variables)arestoredinadictionaryassociatedwith

theclass• •The__dict__dictionaryisnotsharedbetweenAttributes

• Example:•Dogdog dog.weightisequivalentto dog.__dict__[‘weight’]

Page 39: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to
Page 40: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

Dictionaries ClassandClassinstanceshaveseparatedictionaries

Dogdict:{'__module__':'__main__','pprint':<functionpprintat0x10a472ed8>,'__doc__':None,'__init__':<function__init__at0x10a472aa0>}dogdict:{'color':'blue','name':'punk','weight':'100lb'}

Page 41: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

ClassforScientificComputing

Page 42: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

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

Page 43: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

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>)

Page 44: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

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−

≈ − +∫

Page 45: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to

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

−∫

Page 46: OOP principles (again) · OOP principles (again) • encapsulation: hiding design details to make the program clearer and more easily modified later • modularity: the ability to