6. Object-Oriented Programming, II

Transcription

6. Object-OrientedProgramming, IIProgramming and Algorithms IIDegree in BioinformaticsFall 2018

Inheritanceclass Carnivora(Animal): class Canid(Carnivora): class Dog(Canid): class Husky(Dog): class Fox(Canid): class Cat(Carnivora): subclass or child classsuperclass or parent classDog “inherits” all theproperties from Canid, etc.in Python, every class is asubclass of object(in Python 3, you can omitwriting it)class diagram hierarchy2

InheritanceAnimalobjectclass Carnivora(Animal): class Canid(Carnivora): Carnivoraclass Dog(Canid): CatCanidclass Husky(Dog): class Fox(Canid): DogFoxclass Cat(Carnivora): class Cocker(Dog):Cocker3

Inheritancec Cocker(“pluto”) c.say(“woof!”)Animalsay(“woof!”) ? Yes!!objectCarnivora Pluto says woof!say(“woof!”) ? nosay(“woof!”) ?class Carnivora(Animal): def say(self,what):print(self.name,”says “,what)noDogsay(“woof!”) ?noCockerCatCanidFox4

How does inheritance workx.f(parameters) Say x was defined using C( ) (x has type C) Then if C defines method f( ), that code isexecuted Else if the parent of C defines method f( ), thatcode is executed Else if the parent of the parent of C definesmethod f( ), that code is executed Else if object defines method f( ), that code isexecuted Else, error5

How does inheritance workx.attrEither x has an attribute called attr, or it doesn’tError if not defined at this momentIt may have been defined / modified in the classof x or in any of its superclasses6

Method is chosen by the objectclass Animal(object):def init (self,name):self.name namedef talk(self):print("Error:",self.name,"can't talk!")class Cat(Animal):def talk(self):print(self.name,"says: Meeooww!")Note that only Animal has initoperationclass Dog(Animal):def talk(self):print(self.name,"says: Woof!")Cat, Dog, Person could override init ,as is done here with talkWhenever a Cat, a Dog, or a Person iscreated, Python calls init for the newobjectThe init code executed is always thatof Animal, as there is no otherclass Person(Animal):def talk(self):print(self.name,"says:My name is",self.name)7

Method is chosen by the objectclass Animal:def init (self,name):self.name namedef talk(self):print("Error:",self.name,"can't talk!")class Cat(Animal):def talk(self):print(self.name,"says: Meeooww!")class Dog(Animal):def talk(self):print(self.name,"says: Wooof!")class Person(Animal):def talk(self):print(self.name,"says:My name is",self.name)microbe Animal(“Joe Amoeba")microbe.talk()my cat Cat("Garfield")my cat.talk()my dog Dog("Rintintin")my dog.talk()agent 007 Person("Bond, James Bond")agent 007.talk()Output:Error: Joe Amoeba can't talk!Garfield says: Meeooww!Rintintin says: Wooof!Bond, James Bond says: 'My name isBond, James Bond'8

Method is chosen by the objectclass Animal(object):def init (self,name):self.name namedef talk(self):print("Error:",self.name,"can't talk!")class Cat(Animal):def talk(self):print(self.name,"says: Meeooww!")class Dog(Animal):def talk(self):print(self.name,"says: Wooof!")class Person(Animal):def talk(self):print(self.name,"says: My name is",self.name)class Super Dog(Dog):def talk(self):print(self.name,"says:'My name is",self.name,"and I am a geneticallyengineered dog'")milou Super Dog("Milou")milou.talk()Output:Milou says: ‘My name is Milou andI am a genetically engineered dog’9

Calling parent class methodclass A(object):def init (self):print(“init A fields ")class B(A):def init (self):print(“init B fields ")b B()# does NOT initialize A fields10

Calling parent class methodclass A(object):def init (self):print(“init A fields ")class B(A):def init (self):A. init (self) # class method - selfprint(“init B fields ")b B()# initializes A fields, then B fields11

Calling parent class methodclass A(object):def init (self):print(“init A fields ")class B(A):def init (self):super(). init () # no selfprint(“init B fields ")b B()# initializes A fields, then B fieldssuper(): parent class of current object class(more technically, the scope of the current class; that’s why no “self” needed)(better option in case you decide to change A’s name, or add a class C in between)(also allows wizards to do fun stuff see mro() later)12

Useful methodsdir(x) lists all the methods of x p Point(0,1) dir(p)[' class ', ' delattr ', ' dict ', ' dir ', ' doc ', ' eq ',' format ', ' ge ', ' getattribute ', ' gt ', ' hash ', ' init ',' init subclass ', ' le ', ' lt ', ' module ', ' ne ', ' new ',' reduce ', ' reduce ex ', ' repr ', ' setattr ', ' sizeof ',' str ', ' subclasshook ', ' weakref ', 'angle', 'angle to origin','distance to origin', 'mod', 'x', 'y']13

Useful methodsdir(x) lists all the methods of x x 5 dir(x)[' abs ', ' add ', ' and ', ' bool ', ' ceil ', ' class ',' delattr ', ' dir ', ' divmod ', ' doc ', ' eq ', ' float ',' floor ', ' floordiv ', ' format ', ' ge ', ' getattribute ',' getnewargs ', ' gt ', ' hash ', ' index ', ' init ',' init subclass ', ' int ', ' invert ', ' le ', ' lshift ', ' lt ',' mod ', ' mul ', ' ne ', ' neg ', ' new ', ' or ', ' pos ',' pow ', ' radd ', ' rand ', ' rdivmod ', ' reduce ',' reduce ex ', ' repr ', ' rfloordiv ', ' rlshift ', ' rmod ',' rmul ', ' ror ', ' round ', ' rpow ', ' rrshift ', ' rshift ',' rsub ', ' rtruediv ', ' rxor ', ' setattr ', ' sizeof ', ' str ',' sub ', ' subclasshook ', ' truediv ', ' trunc ', ' xor ','bit length', 'conjugate', 'denominator', 'from bytes', 'imag', 'numerator','real', 'to bytes']14

Useful methodsisinstance(object,classname) Trueisinstance(1,int)issubclass(B,A): True if B subclass of Ahasattr(o,’name’): True if o has a property called‘name’ hasattr(p,’mod’)Truesuper() or classname.super(): parent class of anobject or a class (scope of )15

Method Resolution Order (MRO)class A(object):passclass B(A):passclass C(B):passclass D(C):passprint(D.mro())[ class ' main .D' , class ' main .C' , class' main .B' , class ' main .A' , class 'object' ]mro can be modified to interesting effects. Only for wizards16

Multiple inheritanceclass A(object):passclass B(A):passclass C(A):passclass D(B,C):passprint(D.mro())[ class ' main .D' , class ' main .B' , class' main .C' , class ' main .A' , class 'object' ]17

Multiple inheritanceclass C(A,B): C inherits both from A and BOccasionally useful; can also lead to bad designsOK when A, B have no methods in commonOr two super classes of C define same nameCommon names get resolved according to mro()18

Example: Saving an objectclass A(object):def save(self):print("save A attributes")class B(A):def save(self):super().save(self)print("save B attributes")class C(A):def save(self):super().save(self)print("save C attributes")class D(C):def save(self):super().save(self)print("save D attributes")19

Multiple inheritanceclass A(object):def save(self):print("save A attributes")class B(A):def save(self):super().save() # save A attributesprint("then save B attributes")class C(A):def save(self):super().save() # save A attributesprint("then save C attributes")class D(B,C):def save(self):B.save(self) # save A then B attributesC.save(self) # save A then C attributesprint("then save D attributes")# A saved twice!!20

Delegationclass C(A,B): def f( ):self.method from B( )Alternative to multipleinheritance. A must in languagesthat don’t support itC objects are not B object class C(A):def init (self):my B object B()Rather, C objects contain a Bobject that handles calls to C withmethods from Bdef f( ):self.my B object.method from B( )21

Polymorphism“len”, “print” are polymorphic operations(different types implement it; parameter decideswhich implementation is executed) len(lst): length of list lst len(d): number of pairs in dictionary d len(i), with i an integer, is an error len(o) actually calls o. len(o) so it is int’s fault, not len's fault same with print22

Conclusion Inheritance is central to OO Leave it to each object to choose the code to execute for onemethod call Class diagrams Overriding Calling parent’s method Method resolution order Multiple inheritance But why? Design advantages? Labs & Soft. Eng. course Open-Closed principle23

Object-Oriented Programming, II Programming and Algorithms II Degree in Bioinformatics Fall 2018. . Dog“inherits” allthe propertiesfromCanid, etc. in Python, everyclassisa subclassof object (in Python 3, youcan omit writing