0% found this document useful (0 votes)
7 views14 pages

Lecture 25

The document discusses inheritance and polymorphism in object-oriented programming. It describes how subclasses inherit properties from their superclass and how polymorphism allows calling the same method on different subclasses to get different results at runtime depending on the object type.

Uploaded by

Maxi Brad
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)
7 views14 pages

Lecture 25

The document discusses inheritance and polymorphism in object-oriented programming. It describes how subclasses inherit properties from their superclass and how polymorphism allows calling the same method on different subclasses to get different results at runtime depending on the object type.

Uploaded by

Maxi Brad
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/ 14

Computer Science 1001

Lecture 25

Lecture Outline

• Inheritance and Polymorphism

– CS1001 Lecture 25 –
Polymorphism

• Every instance of a subclass is also an instance of


its superclass, but not vice versa.

• For example, every MultipleChoice is a


Question, but not every Question is a
MultipleChoice.

• An object of a subclass can be used wherever its


superclass object is used.

• For example, we can pass an object of a subclass as


an argument to a function that has the superclass
type as a parameter.

• Presenting many versions of a concept by a single


interface is known as polymorphism.

– CS1001 Lecture 25 – 1
Dynamic binding

• How does Python determine which method(s) to


execute when the object type can be different?

• In the case of our showQuestion function, which


display() method is called?

• In the case where the parameter q is a Question,


the display() method in the superclass is called.

• In the case where the parameter q is a


MultipleChoice, the display() method in that
subclass is called.

• Python uses dynamic binding to determine which


method to call.

• Method calls are determined at run-time depending


on the type of object passed in.

– CS1001 Lecture 25 – 2
Dynamic binding

• Python searches for the implementation of the


method being called (for example, display())
starting in the most specific class and continues up
the class hierarchy until it finds an implementation.

• When a match has been found, the search stops


and the first-found implementation is invoked.

• This allows us to easily extend our functionality as


necessary.

• If we were to add another subclass of Question we


would only need to provide the appropriate methods
within our new subclass in order to make use of the
showQuestion function.

– CS1001 Lecture 25 – 3
The repr method

• We have seen how to provide a string representation


of an object by specifying the __str__ special
method. This method provides an informal
description of the object.

• The special method __repr__ also returns the


representation of an object as a string.

• Consider the following class:

class Person:
def __init__(self, first, last, sal):
self._firstname = first
self._lastname = last
self._salary = sal
def getInfo(self):
print(self._firstname + " " + self._lastname +
" your salary is $"+ str(self._salary))

• We have included a getInfo() method which


outputs detail about the class attributes:

>>> from person import *

– CS1001 Lecture 25 – 4
>>> p = Person("John", "Smith", 70000)
>>> p.getInfo()
John Smith your salary is $70000
>>> p
<person.Person object at 0x7fadfe48c470>
>>> print(p)
<person.Person object at 0x7fadfe48c470>

• If we include a __str__ method:

def __str__(self):
return self._firstname + " " + self._lastname +\
" your salary is $"+ str(self._salary)

we get:

>>> from person import *


>>> p = Person("John", "Smith", 70000)
>>> print(p)
John Smith your salary is $70000
>>> p
<person.Person object at 0x7ff8fd03a470>

• Defining a __repr__ method:

def __repr__(self):
return self._firstname + " " + self._lastname +\
" your salary is $"+ str(self._salary + "."

– CS1001 Lecture 25 – 5
produces:

>>> from person import *


>>> p = Person("John", "Smith", 70000)
>>> print(p)
John Smith your salary is $70000
>>> p
John Smith your salary is $70000.

– CS1001 Lecture 25 – 6
Inheritance example

• Consider the following code:

class A:
def __init__(self,i=0):
self.__i = i
def getI(self):
return self.__i

class B(A):
def __init__(self,j=0):
self.j = j

• What happens if the method getI is called from an


object of class B? For example:

b = B()
print(b.getI())

• An error occurs because the data field i is never


created for objects of class B. The superclass
constructor should be called from the subclass
constructor to ensure that all instance variables
are created.

– CS1001 Lecture 25 – 7
Inheritance example
• Consider the following code:
class Person:
def __init__(self,name):
self.__name = name
def getInfo(self):
return "Person" + self.__name
def printPerson(self):
print(self.getInfo())

class Student(Person):
def __init__(self,name,id):
super().__init__(name)
self.__id = id
def getInfo(self):
return "Student" + self.__id

• What happens if printPerson is called from an


object of class Student? For example:
s = Student("Sara","1234")
s.printPerson()

• The printPerson inherited from class Person is


invoked, which will call the getInfo method of
class Student since self refers to s which is of
type Student. Student1234 is printed.

– CS1001 Lecture 25 – 8
Inheritance example

• Suppose you want to represent different types


of bank accounts such as savings accounts and
chequing accounts.

• Both types of accounts have features that are


common to all bank accounts (ex. deposit and
withdraw).

• These common features could be a part of a


BankAccount base class.

• A savings account would earn interest. For example,


interest could be calculated monthly based on the
minimum monthly balance.

• A chequing account does not earn interest but has 3


free withdrawals per month. Additional withdrawals
beyond 3 are charged $1 per withdrawal.

– CS1001 Lecture 25 – 9
Inheritance example
# A bank account has a balance and a mechanism for making deposits
# and withdrawals
class BankAccount :
def __init__(self) :
self._balance = 0.0

def deposit(self, amount) :


self._balance = self._balance + amount

def withdraw(self, amount) :


self._balance = self._balance - amount

def monthEnd(self) :
return

def getBalance(self) :
return self._balance

# A savings account earns interest on the minimum balance.


class SavingsAccount(BankAccount) :
def __init__(self) :
super().__init__()
self._interestRate = 0.0
self._minBalance = 0.0

def setInterestRate(self, rate) :


self._interestRate = rate

– CS1001 Lecture 25 – 10
# Overrides superclass method.
def withdraw(self, amount) :
super().withdraw(amount)
balance = self.getBalance()
if balance < self._minBalance :
self._minBalance = balance

# Overrides superclass method.


def monthEnd(self) :
interest = self._minBalance * self._interestRate / 100
self.deposit(interest)
self._minBalance = self.getBalance()

# A chequing account has a limited number of free withdrawals.


class ChequingAccount(BankAccount) :
def __init__(self) :
super().__init__()
self._withdrawals = 0

# Overrides superclass method.


def withdraw(self, amount) :
FREE_WITHDRAWALS = 3
WITHDRAWAL_FEE = 1

super().withdraw(amount)
self._withdrawals = self._withdrawals + 1
if self._withdrawals > FREE_WITHDRAWALS :
super().withdraw(WITHDRAWAL_FEE)

# Overrides superclass method.


def monthEnd(self) :
self._withdrawals = 0

– CS1001 Lecture 25 – 11
Inheritance example
from accounts import ChequingAccount, SavingsAccount

# Create accounts.
ACCOUNTS_SIZE = 10
accounts = []
for i in range(ACCOUNTS_SIZE // 2) :
accounts.append(ChequingAccount())

for i in range(ACCOUNTS_SIZE // 2) :
account = SavingsAccount()
account.setInterestRate(0.75)
accounts.append(account)

# Execute commands.
done = False
while not done :
action = input("D)eposit W)ithdraw M)onth end Q)uit: ")
action = action.upper()
if action == "D" or action == "W" : # Deposit or withdrawal.
num = int(input("Enter account number: "))
amount = float(input("Enter amount: "))

if action == "D" :
accounts[num].deposit(amount)
else :
accounts[num].withdraw(amount)

print("Balance:", accounts[num].getBalance())
elif action == "M" : # Month end processing.
for n in range(len(accounts)) :

– CS1001 Lecture 25 – 12
accounts[n].monthEnd()
print(n, accounts[n].getBalance())
elif action == "Q" :
done = True

– CS1001 Lecture 25 – 13

You might also like