LECT6
LECT6
Overriding
When inheriting from a class, we can alter the behavior of the original
superclass by "overriding" functions (i.e. declaring functions in the subclass
with the same name).
class Department:
def init ( self ): class Student:
self.students = [] def init ( self,last,first ):
self.lastname = last
def enroll( self, student ): self.firstname = first
self.students.append(student)
Composition
Create Student
>>> compsci = Department()
>>> compsci.enroll( Student( "Smith", "John" ) ) instances and add
>>> compsci.enroll( Student( "Murphy", "Alice" ) ) to Department
instance
>>> for s in compsci.students:
... print (s.firstname,s.lastname)
John Smith
Alice Murphy
Polymorphism
Two objects of different classes but supporting the same set of functions or attributes can be treated
identically.
The implementations may differ internally, but the outward "appearance" is the same.
Polymorphism
Two different classes that contain the function area()
class Rectangle(Shape): class Circle(Shape):
def init (self, w, h): def init (self, rad):
Shape. init (self) Shape. init (self)
self.width = w self.radius = rad
self.height = h
def area(self):
def area(self): return math.pi*(self.radius**2)
return self.width*self.height