SlideShare a Scribd company logo
1 of 48
Basic Inheritance
Damian Gordon
Basic Inheritance
• We have mentioned before that software re-use is considered
one of the golden rules of object-orientated programming, and
that generally speaking we will prefer to eliminate duplicated
code whenever possible.
• One mechanism to achieve this is inheritance.
Basic Inheritance
• Technically all classes are a sub-class of a class called Object,
so they all inherit from that class.
• The class called Object doesn’t really have many attributes
or methods, but they give all other classes their structure.
• If a class doesn’t explicitly inherit from any other class it
implicitly inherits from Object.
Basic Inheritance
• We can explicitly call the Object class as follows:
class MySubClass(object):
pass
# End Class.
Basic Inheritance
• This is inheritance in action.
• We call the object class, the superclass, and the object that
inherits into, the subclass.
• Python is great, because all you need to do to inherit from a
superclass is to include that classes’ name in the calling classes’
declaration.
Basic Inheritance
• Now let’s look at an example in practice.
• Let’s say we have a simple address book program that keeps
track of names and e-mail addresses. We’ll call the class
Contact, and this class keeps the list of all contacts, and
initialises the names and addresses for new contacts:
Basic Inheritance
class Contact:
contacts_list = []
def _ _init_ _(self, name, email):
self.name = name
self.email = email
Contact.contacts_list.append(self)
# End Init
# End Class
Basic Inheritance
class Contact:
contacts_list = []
def _ _init_ _(self, name, email):
self.name = name
self.email = email
Contact.contacts_list.append(self)
# End Init
# End Class
Because contacts_list is
declared here, there is only one
instance of this attribute , and it is
accessed as
Contacts.contact_list.
Basic Inheritance
class Contact:
contacts_list = []
def _ _init_ _(self, name, email):
self.name = name
self.email = email
Contact.contacts_list.append(self)
# End Init
# End Class
Because contacts_list is
declared here, there is only one
instance of this attribute , and it is
accessed as
Contacts.contact_list.
Append the newly instantiated
Contact to the contacts_list.
Basic Inheritance
name
__init__( )
email
contacts_list[ ]
Basic Inheritance
• Now let’s say that the contact list is for our company, and some
of our contacts are suppliers and some others are other staff
members in the company.
• If we wanted to add an order method, so that we can order
supplies off our suppliers, we better do it in such a way as we
cannot try to accidently order supplies off other staff
members. Here’s how we do it:
Basic Inheritance
class Supplier(Contact):
def order(self, order):
print(“The order will send ”
“’{}’ order to ‘{}’”.format(order,self.name))
# End order.
# End Class
Basic Inheritance
class Supplier(Contact):
def order(self, order):
print(“The order will send ”
“’{}’ order to ‘{}’”.format(order,self.name))
# End order.
# End Class
Create a new class called Supplier,
that has all the methods and
attributes of the Contact class. Now
add a new method called order.
Basic Inheritance
class Supplier(Contact):
def order(self, order):
print(“The order will send ”
“’{}’ order to ‘{}’”.format(order,self.name))
# End order.
# End Class
Create a new class called Supplier,
that has all the methods and
attributes of the Contact class. Now
add a new method called order.
Print out what was ordered from what
supplier.
Basic Inheritance
name
__init__( )
email
contacts_list[ ]
Basic Inheritance
name
__init__( )
email
contacts_list[ ]
order( )
Basic Inheritance
• Let’s run this, first we’ll declare some instances:
c1 = Contact("Tom StaffMember", "TomStaffMember@MyCompany.com")
c2 = Contact("Fred StaffMember", "FredStaffMember@MyCompany.com")
s1 = Supplier("Joe Supplier", "JoeSupplier@Supplies.com")
s2 = Supplier("John Supplier", "JohnSupplier@Supplies.com")
Basic Inheritance
• Now let’s check if that has been declared correctly:
print("Our Staff Members are:“, c1.name, " ", c2.name)
print("Their email addresses are:“, c1.email, " ", c2.email)
print("Our Suppliers are:“, s1.name, " ", s2.name)
print("Their email addresses are:“, s1.email, " ", s2.email)
Basic Inheritance
• We can order from suppliers:
s1.order("Bag of sweets")
s2.order("Boiled eggs")
Basic Inheritance
• We can order from suppliers:
s1.order("Bag of sweets")
s2.order("Boiled eggs")
The order will send our 'Bag of sweets' order to 'Joe Supplier'
The order will send our 'Boiled eggs' order to 'John Supplier'
Basic Inheritance
• But we can’t order from staff members (they don’t have the
contact method:
c1.order("Bag of sweets")
c2.order("Boiled eggs")
Basic Inheritance
• But we can’t order from staff members (they don’t have the
contact method:
c1.order("Bag of sweets")
c2.order("Boiled eggs")
Traceback (most recent call last):
File "C:/Users/damian.gordon/AppData/Local/Programs/Python/Python35-
32/Inheritance.py", line 64, in <module>
c1.order("Bag of sweets")
AttributeError: 'Contact' object has no attribute 'order'
name
__init__( )
email
contacts_list[ ]
name
__init__( )
email
contacts_list[ ]
order( )
Extending Built-Ins
Extending Built-Ins
• Let’s say we needed to add a new method that searches the
contacts_list for a particular name, where would we put
that method?
• It seems like something that might be better associated with
the list itself, so how would we do that?
Extending Built-Ins
class ContactList(list):
def search(self, name):
“Return any search hits”
matching_contacts = [ ]
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
# Endif;
# Endfor;
return matching_contacts
# End Search
# End Class
Extending Built-Ins
class ContactList(list):
def search(self, name):
“Return any search hits”
matching_contacts = [ ]
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
# Endif;
# Endfor;
return matching_contacts
# End Search
# End Class
This is a new class that
builds on the list type.
Extending Built-Ins
class ContactList(list):
def search(self, name):
“Return any search hits”
matching_contacts = [ ]
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
# Endif;
# Endfor;
return matching_contacts
# End Search
# End Class
This is a new class that
builds on the list type.
Create a new list of
matching names.
Extending Built-Ins
class Contact(list):
contacts_list = ContactList()
def _ _init_ _(self, name, email):
self.name = name
self.email = email
self.contacts_list.append(self)
# End Init
# End Class
Extending Built-Ins
class Contact(list):
contacts_list = ContactList()
def _ _init_ _(self, name, email):
self.name = name
self.email = email
self.contacts_list.append(self)
# End Init
# End Class
Instead of declaring
contacts_list as a list we
declare it as a class that
inherits from list.
Extending Built-Ins
• Let’s run this, first we’ll declare some instances, and then do a
search:
c1 = Contact("Tom StaffMember", "TomStaffMember@MyCompany.com")
c2 = Contact("Fred StaffMember", "FredStaffMember@MyCompany.com")
c3 = Contact("Anne StaffMember", "AnneStaffMember@MyCompany.com")
SearchName = input("Who would you like to search for?n")
print([c.name for c in Contact.contacts_list.search(SearchName)])
Extending Built-Ins
• Let’s run this, first we’ll declare some instances, and then do a
search:
c1 = Contact("Tom StaffMember", "TomStaffMember@MyCompany.com")
c2 = Contact("Fred StaffMember", "FredStaffMember@MyCompany.com")
c3 = Contact("Anne StaffMember", "AnneStaffMember@MyCompany.com")
SearchName = input("Who would you like to search for?n")
print([c.name for c in Contact.contacts_list.search(SearchName)])
>>> Who would you like to search for?
Staff
['Tom StaffMember', 'Fred StaffMember', 'Anne StaffMember']
Overriding and super
Overriding and super
• So inheritance is used to add new behaviours, but what if we
want to change behaviours?
• Let’s look at the Supplier class again, and we want to
change how the order method works.
Overriding and super
• Here’s what we have so far:
class Supplier(Contact):
def order(self, order):
print("The order will send our "
"'{}' order to '{}'".format(order,self.name))
# End order.
# End Class
Overriding and super
• Here’s a new version:
class SupplierCheck(Supplier):
def order(self, order, balance):
if balance < 0:
# THEN
print("This customer is in debt.")
else:
print("The order will send our "
"'{}' order to '{}'".format(order,self.name))
# End order.
# End Class
Overriding and super
• Here’s a new version:
class SupplierCheck(Supplier):
def order(self, order, balance):
if balance < 0:
# THEN
print("This customer is in debt.")
else:
print("The order will send our "
"'{}' order to '{}'".format(order,self.name))
# End order.
# End Class
Overriding and super
• Here’s a new version:
class SupplierCheck(Supplier):
def order(self, order, balance):
if balance < 0:
# THEN
print("This customer is in debt.")
else:
print("The order will send our "
"'{}' order to '{}'".format(order,self.name))
# End order.
# End Class
The new class inherits from
the Supplier class. It is
therefore a subclass of it.
Overriding and super
• Here’s a new version:
class SupplierCheck(Supplier):
def order(self, order, balance):
if balance < 0:
# THEN
print("This customer is in debt.")
else:
print("The order will send our "
"'{}' order to '{}'".format(order,self.name))
# End order.
# End Class
The new class inherits from
the Supplier class. It is
therefore a subclass of it.
And it overrides the order
method to now explore the
new balance attribute.
Overriding and super
• We declare objects as follows:
s1 = Supplier("Joe Supplier", "JoeSupplier@Supplies.com")
s2 = Supplier("John Supplier", "JohnSupplier@Supplies.com")
s3 = SupplierCheck("Anne Supplier", "AnneSupplier@Supplies.com")
s4 = SupplierCheck("Mary Supplier", "MarySupplier@Supplies.com")
Overriding and super
• And when we call the new order method:
s1.order("Bag of sweets")
s2.order("Boiled eggs")
s3.order("Coffee", 23)
s4.order("Corn Flakes", -12)
Overriding and super
• And when we call the new order method:
s1.order("Bag of sweets")
s2.order("Boiled eggs")
s3.order("Coffee", 23)
s4.order("Corn Flakes", -12)
The order will send our 'Bag of sweets' order to 'Joe Supplier'
The order will send our 'Boiled eggs' order to 'John Supplier'
The order will send our 'Coffee' order to 'Anne Supplier'
This customer is in debt.
Overriding and super
• The only problem with this approach is that the superclass and
the subclass both have similar code in them concerning the
order method.
• So if at some point in the future we have to change that
common part of the method, we have to remember to change
it in two places.
• It is better if we can just have the similar code in one place.
Overriding and super
• We can do this using the super( ) class.
• The super( ) class calls the superclass method from the
subclass.
• Let’s look at how we had it:
Overriding and super
• Here’s overridng:
class SupplierCheck(Supplier):
def order(self, order, balance):
if balance < 0:
# THEN
print("This customer is in debt.")
else:
print("The order will send our "
"'{}' order to '{}'".format(order,self.name))
# End order.
# End Class
Overriding and super
• Here’s super:
class SupplierCheck(Supplier):
def order(self, order, balance):
if balance < 0:
# THEN
print("This customer is in debt.")
else:
super().order(order)
# End order.
# End Class
Overriding and super
• Here’s super:
class SupplierCheck(Supplier):
def order(self, order, balance):
if balance < 0:
# THEN
print("This customer is in debt.")
else:
super().order(order)
# End order.
# End Class
Call the order method in the
superclass of
SupplierCheck, so call
Supplier.order(order).
etc.

More Related Content

What's hot

Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructorsPraveen M Jigajinni
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python Home
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and PackagesDamian T. Gordon
 
What Are Python Modules? Edureka
What Are Python Modules? EdurekaWhat Are Python Modules? Edureka
What Are Python Modules? EdurekaEdureka!
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in pythonTMARAGATHAM
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 

What's hot (20)

Python-DataAbstarction.pptx
Python-DataAbstarction.pptxPython-DataAbstarction.pptx
Python-DataAbstarction.pptx
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructors
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
What Are Python Modules? Edureka
What Are Python Modules? EdurekaWhat Are Python Modules? Edureka
What Are Python Modules? Edureka
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 

Viewers also liked

Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party LibrariesDamian T. Gordon
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator PatternDamian T. Gordon
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple InheritanceDamian T. Gordon
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programmingDamian T. Gordon
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in PythonDamian T. Gordon
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingDamian T. Gordon
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) ModelDamian T. Gordon
 

Viewers also liked (12)

Python: Design Patterns
Python: Design PatternsPython: Design Patterns
Python: Design Patterns
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party Libraries
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator Pattern
 
Object-Orientated Design
Object-Orientated DesignObject-Orientated Design
Object-Orientated Design
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
 
Python: Access Control
Python: Access ControlPython: Access Control
Python: Access Control
 
Python: Manager Objects
Python: Manager ObjectsPython: Manager Objects
Python: Manager Objects
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
 
Python: Polymorphism
Python: PolymorphismPython: Polymorphism
Python: Polymorphism
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented Programming
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) Model
 

Similar to Python: Basic Inheritance

Advanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID PrinciplesAdvanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID PrinciplesJon Kruger
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2Ahmad Hussein
 
Testing Has Many Purposes
Testing Has Many PurposesTesting Has Many Purposes
Testing Has Many PurposesAlex Sharp
 
Write codeforhumans
Write codeforhumansWrite codeforhumans
Write codeforhumansNarendran R
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Brian Hogan
 
4.7 Automate Loading Data with Little to No Duplicates!
4.7 Automate Loading Data with Little to No Duplicates!4.7 Automate Loading Data with Little to No Duplicates!
4.7 Automate Loading Data with Little to No Duplicates!TargetX
 
Dependency Injection in Spring
Dependency Injection in SpringDependency Injection in Spring
Dependency Injection in SpringASG
 
Notes5
Notes5Notes5
Notes5hccit
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala MakeoverGarth Gilmour
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelpauldix
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelpauldix
 
The Ring programming language version 1.5.3 book - Part 83 of 184
The Ring programming language version 1.5.3 book - Part 83 of 184The Ring programming language version 1.5.3 book - Part 83 of 184
The Ring programming language version 1.5.3 book - Part 83 of 184Mahmoud Samir Fayed
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::ManagerJay Shirley
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for KidsAimee Maree Forsstrom
 
Double Trouble
Double TroubleDouble Trouble
Double Troublegsterndale
 
Django in the Office: Get Your Admin for Nothing and Your SQL for Free
Django in the Office: Get Your Admin for Nothing and Your SQL for FreeDjango in the Office: Get Your Admin for Nothing and Your SQL for Free
Django in the Office: Get Your Admin for Nothing and Your SQL for FreeHarvard Web Working Group
 
powerpoint 2-7.pptx
powerpoint 2-7.pptxpowerpoint 2-7.pptx
powerpoint 2-7.pptxJuanPicasso7
 

Similar to Python: Basic Inheritance (20)

Advanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID PrinciplesAdvanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID Principles
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2
 
Testing Has Many Purposes
Testing Has Many PurposesTesting Has Many Purposes
Testing Has Many Purposes
 
Write codeforhumans
Write codeforhumansWrite codeforhumans
Write codeforhumans
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
 
4.7 Automate Loading Data with Little to No Duplicates!
4.7 Automate Loading Data with Little to No Duplicates!4.7 Automate Loading Data with Little to No Duplicates!
4.7 Automate Loading Data with Little to No Duplicates!
 
Dependency Injection in Spring
Dependency Injection in SpringDependency Injection in Spring
Dependency Injection in Spring
 
Notes5
Notes5Notes5
Notes5
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
Refactoring
RefactoringRefactoring
Refactoring
 
The Ring programming language version 1.5.3 book - Part 83 of 184
The Ring programming language version 1.5.3 book - Part 83 of 184The Ring programming language version 1.5.3 book - Part 83 of 184
The Ring programming language version 1.5.3 book - Part 83 of 184
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Double Trouble
Double TroubleDouble Trouble
Double Trouble
 
Django in the Office: Get Your Admin for Nothing and Your SQL for Free
Django in the Office: Get Your Admin for Nothing and Your SQL for FreeDjango in the Office: Get Your Admin for Nothing and Your SQL for Free
Django in the Office: Get Your Admin for Nothing and Your SQL for Free
 
powerpoint 2-7.pptx
powerpoint 2-7.pptxpowerpoint 2-7.pptx
powerpoint 2-7.pptx
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
 
Values
ValuesValues
Values
 

More from Damian T. Gordon

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Damian T. Gordon
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to MicroservicesDamian T. Gordon
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud ComputingDamian T. Gordon
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSDamian T. Gordon
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOTDamian T. Gordon
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricDamian T. Gordon
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDamian T. Gordon
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSUREDamian T. Gordon
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDamian T. Gordon
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDamian T. Gordon
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDamian T. Gordon
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsDamian T. Gordon
 

More from Damian T. Gordon (20)

Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.Universal Design for Learning, Co-Designing with Students.
Universal Design for Learning, Co-Designing with Students.
 
Introduction to Microservices
Introduction to MicroservicesIntroduction to Microservices
Introduction to Microservices
 
REST and RESTful Services
REST and RESTful ServicesREST and RESTful Services
REST and RESTful Services
 
Serverless Computing
Serverless ComputingServerless Computing
Serverless Computing
 
Cloud Identity Management
Cloud Identity ManagementCloud Identity Management
Cloud Identity Management
 
Containers and Docker
Containers and DockerContainers and Docker
Containers and Docker
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud Computing
 
Introduction to ChatGPT
Introduction to ChatGPTIntroduction to ChatGPT
Introduction to ChatGPT
 
How to Argue Logically
How to Argue LogicallyHow to Argue Logically
How to Argue Logically
 
Evaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONSEvaluating Teaching: SECTIONS
Evaluating Teaching: SECTIONS
 
Evaluating Teaching: MERLOT
Evaluating Teaching: MERLOTEvaluating Teaching: MERLOT
Evaluating Teaching: MERLOT
 
Evaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson RubricEvaluating Teaching: Anstey and Watson Rubric
Evaluating Teaching: Anstey and Watson Rubric
 
Evaluating Teaching: LORI
Evaluating Teaching: LORIEvaluating Teaching: LORI
Evaluating Teaching: LORI
 
Designing Teaching: Pause Procedure
Designing Teaching: Pause ProcedureDesigning Teaching: Pause Procedure
Designing Teaching: Pause Procedure
 
Designing Teaching: ADDIE
Designing Teaching: ADDIEDesigning Teaching: ADDIE
Designing Teaching: ADDIE
 
Designing Teaching: ASSURE
Designing Teaching: ASSUREDesigning Teaching: ASSURE
Designing Teaching: ASSURE
 
Designing Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning TypesDesigning Teaching: Laurilliard's Learning Types
Designing Teaching: Laurilliard's Learning Types
 
Designing Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of InstructionDesigning Teaching: Gagne's Nine Events of Instruction
Designing Teaching: Gagne's Nine Events of Instruction
 
Designing Teaching: Elaboration Theory
Designing Teaching: Elaboration TheoryDesigning Teaching: Elaboration Theory
Designing Teaching: Elaboration Theory
 
Universally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some ConsiderationsUniversally Designed Learning Spaces: Some Considerations
Universally Designed Learning Spaces: Some Considerations
 

Recently uploaded

Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 

Recently uploaded (20)

Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 

Python: Basic Inheritance

  • 2. Basic Inheritance • We have mentioned before that software re-use is considered one of the golden rules of object-orientated programming, and that generally speaking we will prefer to eliminate duplicated code whenever possible. • One mechanism to achieve this is inheritance.
  • 3. Basic Inheritance • Technically all classes are a sub-class of a class called Object, so they all inherit from that class. • The class called Object doesn’t really have many attributes or methods, but they give all other classes their structure. • If a class doesn’t explicitly inherit from any other class it implicitly inherits from Object.
  • 4. Basic Inheritance • We can explicitly call the Object class as follows: class MySubClass(object): pass # End Class.
  • 5. Basic Inheritance • This is inheritance in action. • We call the object class, the superclass, and the object that inherits into, the subclass. • Python is great, because all you need to do to inherit from a superclass is to include that classes’ name in the calling classes’ declaration.
  • 6. Basic Inheritance • Now let’s look at an example in practice. • Let’s say we have a simple address book program that keeps track of names and e-mail addresses. We’ll call the class Contact, and this class keeps the list of all contacts, and initialises the names and addresses for new contacts:
  • 7. Basic Inheritance class Contact: contacts_list = [] def _ _init_ _(self, name, email): self.name = name self.email = email Contact.contacts_list.append(self) # End Init # End Class
  • 8. Basic Inheritance class Contact: contacts_list = [] def _ _init_ _(self, name, email): self.name = name self.email = email Contact.contacts_list.append(self) # End Init # End Class Because contacts_list is declared here, there is only one instance of this attribute , and it is accessed as Contacts.contact_list.
  • 9. Basic Inheritance class Contact: contacts_list = [] def _ _init_ _(self, name, email): self.name = name self.email = email Contact.contacts_list.append(self) # End Init # End Class Because contacts_list is declared here, there is only one instance of this attribute , and it is accessed as Contacts.contact_list. Append the newly instantiated Contact to the contacts_list.
  • 11. Basic Inheritance • Now let’s say that the contact list is for our company, and some of our contacts are suppliers and some others are other staff members in the company. • If we wanted to add an order method, so that we can order supplies off our suppliers, we better do it in such a way as we cannot try to accidently order supplies off other staff members. Here’s how we do it:
  • 12. Basic Inheritance class Supplier(Contact): def order(self, order): print(“The order will send ” “’{}’ order to ‘{}’”.format(order,self.name)) # End order. # End Class
  • 13. Basic Inheritance class Supplier(Contact): def order(self, order): print(“The order will send ” “’{}’ order to ‘{}’”.format(order,self.name)) # End order. # End Class Create a new class called Supplier, that has all the methods and attributes of the Contact class. Now add a new method called order.
  • 14. Basic Inheritance class Supplier(Contact): def order(self, order): print(“The order will send ” “’{}’ order to ‘{}’”.format(order,self.name)) # End order. # End Class Create a new class called Supplier, that has all the methods and attributes of the Contact class. Now add a new method called order. Print out what was ordered from what supplier.
  • 17. Basic Inheritance • Let’s run this, first we’ll declare some instances: c1 = Contact("Tom StaffMember", "TomStaffMember@MyCompany.com") c2 = Contact("Fred StaffMember", "FredStaffMember@MyCompany.com") s1 = Supplier("Joe Supplier", "JoeSupplier@Supplies.com") s2 = Supplier("John Supplier", "JohnSupplier@Supplies.com")
  • 18. Basic Inheritance • Now let’s check if that has been declared correctly: print("Our Staff Members are:“, c1.name, " ", c2.name) print("Their email addresses are:“, c1.email, " ", c2.email) print("Our Suppliers are:“, s1.name, " ", s2.name) print("Their email addresses are:“, s1.email, " ", s2.email)
  • 19. Basic Inheritance • We can order from suppliers: s1.order("Bag of sweets") s2.order("Boiled eggs")
  • 20. Basic Inheritance • We can order from suppliers: s1.order("Bag of sweets") s2.order("Boiled eggs") The order will send our 'Bag of sweets' order to 'Joe Supplier' The order will send our 'Boiled eggs' order to 'John Supplier'
  • 21. Basic Inheritance • But we can’t order from staff members (they don’t have the contact method: c1.order("Bag of sweets") c2.order("Boiled eggs")
  • 22. Basic Inheritance • But we can’t order from staff members (they don’t have the contact method: c1.order("Bag of sweets") c2.order("Boiled eggs") Traceback (most recent call last): File "C:/Users/damian.gordon/AppData/Local/Programs/Python/Python35- 32/Inheritance.py", line 64, in <module> c1.order("Bag of sweets") AttributeError: 'Contact' object has no attribute 'order'
  • 23. name __init__( ) email contacts_list[ ] name __init__( ) email contacts_list[ ] order( )
  • 25. Extending Built-Ins • Let’s say we needed to add a new method that searches the contacts_list for a particular name, where would we put that method? • It seems like something that might be better associated with the list itself, so how would we do that?
  • 26. Extending Built-Ins class ContactList(list): def search(self, name): “Return any search hits” matching_contacts = [ ] for contact in self: if name in contact.name: matching_contacts.append(contact) # Endif; # Endfor; return matching_contacts # End Search # End Class
  • 27. Extending Built-Ins class ContactList(list): def search(self, name): “Return any search hits” matching_contacts = [ ] for contact in self: if name in contact.name: matching_contacts.append(contact) # Endif; # Endfor; return matching_contacts # End Search # End Class This is a new class that builds on the list type.
  • 28. Extending Built-Ins class ContactList(list): def search(self, name): “Return any search hits” matching_contacts = [ ] for contact in self: if name in contact.name: matching_contacts.append(contact) # Endif; # Endfor; return matching_contacts # End Search # End Class This is a new class that builds on the list type. Create a new list of matching names.
  • 29. Extending Built-Ins class Contact(list): contacts_list = ContactList() def _ _init_ _(self, name, email): self.name = name self.email = email self.contacts_list.append(self) # End Init # End Class
  • 30. Extending Built-Ins class Contact(list): contacts_list = ContactList() def _ _init_ _(self, name, email): self.name = name self.email = email self.contacts_list.append(self) # End Init # End Class Instead of declaring contacts_list as a list we declare it as a class that inherits from list.
  • 31. Extending Built-Ins • Let’s run this, first we’ll declare some instances, and then do a search: c1 = Contact("Tom StaffMember", "TomStaffMember@MyCompany.com") c2 = Contact("Fred StaffMember", "FredStaffMember@MyCompany.com") c3 = Contact("Anne StaffMember", "AnneStaffMember@MyCompany.com") SearchName = input("Who would you like to search for?n") print([c.name for c in Contact.contacts_list.search(SearchName)])
  • 32. Extending Built-Ins • Let’s run this, first we’ll declare some instances, and then do a search: c1 = Contact("Tom StaffMember", "TomStaffMember@MyCompany.com") c2 = Contact("Fred StaffMember", "FredStaffMember@MyCompany.com") c3 = Contact("Anne StaffMember", "AnneStaffMember@MyCompany.com") SearchName = input("Who would you like to search for?n") print([c.name for c in Contact.contacts_list.search(SearchName)]) >>> Who would you like to search for? Staff ['Tom StaffMember', 'Fred StaffMember', 'Anne StaffMember']
  • 34. Overriding and super • So inheritance is used to add new behaviours, but what if we want to change behaviours? • Let’s look at the Supplier class again, and we want to change how the order method works.
  • 35. Overriding and super • Here’s what we have so far: class Supplier(Contact): def order(self, order): print("The order will send our " "'{}' order to '{}'".format(order,self.name)) # End order. # End Class
  • 36. Overriding and super • Here’s a new version: class SupplierCheck(Supplier): def order(self, order, balance): if balance < 0: # THEN print("This customer is in debt.") else: print("The order will send our " "'{}' order to '{}'".format(order,self.name)) # End order. # End Class
  • 37. Overriding and super • Here’s a new version: class SupplierCheck(Supplier): def order(self, order, balance): if balance < 0: # THEN print("This customer is in debt.") else: print("The order will send our " "'{}' order to '{}'".format(order,self.name)) # End order. # End Class
  • 38. Overriding and super • Here’s a new version: class SupplierCheck(Supplier): def order(self, order, balance): if balance < 0: # THEN print("This customer is in debt.") else: print("The order will send our " "'{}' order to '{}'".format(order,self.name)) # End order. # End Class The new class inherits from the Supplier class. It is therefore a subclass of it.
  • 39. Overriding and super • Here’s a new version: class SupplierCheck(Supplier): def order(self, order, balance): if balance < 0: # THEN print("This customer is in debt.") else: print("The order will send our " "'{}' order to '{}'".format(order,self.name)) # End order. # End Class The new class inherits from the Supplier class. It is therefore a subclass of it. And it overrides the order method to now explore the new balance attribute.
  • 40. Overriding and super • We declare objects as follows: s1 = Supplier("Joe Supplier", "JoeSupplier@Supplies.com") s2 = Supplier("John Supplier", "JohnSupplier@Supplies.com") s3 = SupplierCheck("Anne Supplier", "AnneSupplier@Supplies.com") s4 = SupplierCheck("Mary Supplier", "MarySupplier@Supplies.com")
  • 41. Overriding and super • And when we call the new order method: s1.order("Bag of sweets") s2.order("Boiled eggs") s3.order("Coffee", 23) s4.order("Corn Flakes", -12)
  • 42. Overriding and super • And when we call the new order method: s1.order("Bag of sweets") s2.order("Boiled eggs") s3.order("Coffee", 23) s4.order("Corn Flakes", -12) The order will send our 'Bag of sweets' order to 'Joe Supplier' The order will send our 'Boiled eggs' order to 'John Supplier' The order will send our 'Coffee' order to 'Anne Supplier' This customer is in debt.
  • 43. Overriding and super • The only problem with this approach is that the superclass and the subclass both have similar code in them concerning the order method. • So if at some point in the future we have to change that common part of the method, we have to remember to change it in two places. • It is better if we can just have the similar code in one place.
  • 44. Overriding and super • We can do this using the super( ) class. • The super( ) class calls the superclass method from the subclass. • Let’s look at how we had it:
  • 45. Overriding and super • Here’s overridng: class SupplierCheck(Supplier): def order(self, order, balance): if balance < 0: # THEN print("This customer is in debt.") else: print("The order will send our " "'{}' order to '{}'".format(order,self.name)) # End order. # End Class
  • 46. Overriding and super • Here’s super: class SupplierCheck(Supplier): def order(self, order, balance): if balance < 0: # THEN print("This customer is in debt.") else: super().order(order) # End order. # End Class
  • 47. Overriding and super • Here’s super: class SupplierCheck(Supplier): def order(self, order, balance): if balance < 0: # THEN print("This customer is in debt.") else: super().order(order) # End order. # End Class Call the order method in the superclass of SupplierCheck, so call Supplier.order(order).
  • 48. etc.