0% found this document useful (0 votes)
4 views

LECT6

Uploaded by

norantharwat58
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

LECT6

Uploaded by

norantharwat58
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

OOP

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

Functions in a subclass take precedence over functions in a superclass.


Overriding
class CustomCounter(Counter):
class Counter: def init (self,size):
def init (self): Counter. init (self)
self.value = 0 self.stepsize = size

def increment(self): def increment(self):


self.value += 1 Overriding self.value += self.stepsize

>>> cc = CustomCounter(4) Calls increment()


>>> cc.increment() on CustomCounter
>>> cc.print_current() not Counter
Current value is 4
Composition
Classes can be built from other smaller classes,allowing us
to model relationships of the type "x has a y” (e.g. a
department has students).

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

Instances of the two classes can be >>> l = []


treated identically... >>> l.append( Rectangle(4,5) )
>>> l.append( Circle(3) )
>>> for someshape in l:
... print someshape.area()
...
Result of area() in Rectangle 20
Result of area() in Circle 28.2743338823

You might also like