SlideShare a Scribd company logo
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 (20)

Java Beans
Java BeansJava Beans
Java Beans
Ankit Desai
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
Lalitkumar_98
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
python Function
python Function python Function
python Function
Ronak Rathi
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Abhilash Nair
 
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!
 
Array in c#
Array in c#Array in c#
Array in c#
Prem Kumar Badri
 
Map, Filter and Reduce In Python
Map, Filter and Reduce In PythonMap, Filter and Reduce In Python
Map, Filter and Reduce In Python
Simplilearn
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
Bhavik Vashi
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
Bhanwar Singh Meena
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
Darpan Chelani
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
Padma Kannan
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
kunal kishore
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
Lalitkumar_98
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
python Function
python Function python Function
python Function
Ronak Rathi
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
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!
 
Map, Filter and Reduce In Python
Map, Filter and Reduce In PythonMap, Filter and Reduce In Python
Map, Filter and Reduce In Python
Simplilearn
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
Bhavik Vashi
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
Bhanwar Singh Meena
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
Padma Kannan
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
kunal kishore
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 

Viewers also liked (12)

Python: Design Patterns
Python: Design PatternsPython: Design Patterns
Python: Design Patterns
Damian T. Gordon
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party Libraries
Damian T. Gordon
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator Pattern
Damian T. Gordon
 
Object-Orientated Design
Object-Orientated DesignObject-Orientated Design
Object-Orientated Design
Damian T. Gordon
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
Damian T. Gordon
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
Damian T. Gordon
 
Python: Access Control
Python: Access ControlPython: Access Control
Python: Access Control
Damian T. Gordon
 
Python: Manager Objects
Python: Manager ObjectsPython: Manager Objects
Python: Manager Objects
Damian T. Gordon
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian T. Gordon
 
Python: Polymorphism
Python: PolymorphismPython: Polymorphism
Python: Polymorphism
Damian 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 Programming
Damian T. Gordon
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) Model
Damian T. Gordon
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party Libraries
Damian T. Gordon
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator Pattern
Damian T. Gordon
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
Damian T. Gordon
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
Damian T. Gordon
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian 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 Programming
Damian T. Gordon
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) Model
Damian T. Gordon
 
Ad

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
Jon Kruger
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2
Ahmad Hussein
 
Testing Has Many Purposes
Testing Has Many PurposesTesting Has Many Purposes
Testing Has Many Purposes
Alex Sharp
 
Write codeforhumans
Write codeforhumansWrite codeforhumans
Write codeforhumans
Narendran R
 
what is class in C++ and classes_objects.ppt
what is class in C++ and classes_objects.pptwhat is class in C++ and classes_objects.ppt
what is class in C++ and classes_objects.ppt
malikliyaqathusain
 
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
Brian 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 Spring
ASG
 
Notes5
Notes5Notes5
Notes5
hccit
 
functions _
functions                                 _functions                                 _
functions _
SwatiHans10
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
Garth Gilmour
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
pauldix
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
pauldix
 
Refactoring
RefactoringRefactoring
Refactoring
Bruno Quintella
 
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
Mahmoud Samir Fayed
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
Jay Shirley
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
Aimee Maree Forsstrom
 
Double Trouble
Double TroubleDouble Trouble
Double Trouble
gsterndale
 
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
Harvard Web Working Group
 
powerpoint 2-7.pptx
powerpoint 2-7.pptxpowerpoint 2-7.pptx
powerpoint 2-7.pptx
JuanPicasso7
 
Advanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID PrinciplesAdvanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID Principles
Jon Kruger
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2
Ahmad Hussein
 
Testing Has Many Purposes
Testing Has Many PurposesTesting Has Many Purposes
Testing Has Many Purposes
Alex Sharp
 
Write codeforhumans
Write codeforhumansWrite codeforhumans
Write codeforhumans
Narendran R
 
what is class in C++ and classes_objects.ppt
what is class in C++ and classes_objects.pptwhat is class in C++ and classes_objects.ppt
what is class in C++ and classes_objects.ppt
malikliyaqathusain
 
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
Brian 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 Spring
ASG
 
Notes5
Notes5Notes5
Notes5
hccit
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
Garth Gilmour
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
pauldix
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
pauldix
 
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
Mahmoud Samir Fayed
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
Jay Shirley
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
Aimee Maree Forsstrom
 
Double Trouble
Double TroubleDouble Trouble
Double Trouble
gsterndale
 
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
Harvard Web Working Group
 
powerpoint 2-7.pptx
powerpoint 2-7.pptxpowerpoint 2-7.pptx
powerpoint 2-7.pptx
JuanPicasso7
 
Ad

More from Damian T. Gordon (20)

Introduction to Prompts and Prompt Engineering
Introduction to Prompts and Prompt EngineeringIntroduction to Prompts and Prompt Engineering
Introduction to Prompts and Prompt Engineering
Damian T. Gordon
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
TRIZ: Theory of Inventive Problem Solving
TRIZ: Theory of Inventive Problem SolvingTRIZ: Theory of Inventive Problem Solving
TRIZ: Theory of Inventive Problem Solving
Damian T. Gordon
 
Some Ethical Considerations of AI and GenAI
Some Ethical Considerations of AI and GenAISome Ethical Considerations of AI and GenAI
Some Ethical Considerations of AI and GenAI
Damian T. Gordon
 
Some Common Errors that Generative AI Produces
Some Common Errors that Generative AI ProducesSome Common Errors that Generative AI Produces
Some Common Errors that Generative AI Produces
Damian T. Gordon
 
The Use of Data and Datasets in Data Science
The Use of Data and Datasets in Data ScienceThe Use of Data and Datasets in Data Science
The Use of Data and Datasets in Data Science
Damian T. Gordon
 
A History of Different Versions of Microsoft Windows
A History of Different Versions of Microsoft WindowsA History of Different Versions of Microsoft Windows
A History of Different Versions of Microsoft Windows
Damian T. Gordon
 
Writing an Abstract: A Question-based Approach
Writing an Abstract: A Question-based ApproachWriting an Abstract: A Question-based Approach
Writing an Abstract: A Question-based Approach
Damian T. Gordon
 
Using GenAI for Universal Design for Learning
Using GenAI for Universal Design for LearningUsing GenAI for Universal Design for Learning
Using GenAI for Universal Design for Learning
Damian T. Gordon
 
A CheckSheet for Inclusive Software Design
A CheckSheet for Inclusive Software DesignA CheckSheet for Inclusive Software Design
A CheckSheet for Inclusive Software Design
Damian T. Gordon
 
A History of Versions of the Apple MacOS
A History of Versions of the Apple MacOSA History of Versions of the Apple MacOS
A History of Versions of the Apple MacOS
Damian T. Gordon
 
68 Ways that Data Science and AI can help address the UN Sustainability Goals
68 Ways that Data Science and AI can help address the UN Sustainability Goals68 Ways that Data Science and AI can help address the UN Sustainability Goals
68 Ways that Data Science and AI can help address the UN Sustainability Goals
Damian T. Gordon
 
Copyright and Creative Commons Considerations
Copyright and Creative Commons ConsiderationsCopyright and Creative Commons Considerations
Copyright and Creative Commons Considerations
Damian T. Gordon
 
Exam Preparation: Some Ideas and Suggestions
Exam Preparation: Some Ideas and SuggestionsExam Preparation: Some Ideas and Suggestions
Exam Preparation: Some Ideas and Suggestions
Damian T. Gordon
 
Studying and Notetaking: Some Suggestions
Studying and Notetaking: Some SuggestionsStudying and Notetaking: Some Suggestions
Studying and Notetaking: Some Suggestions
Damian T. Gordon
 
The Growth Mindset: Explanations and Activities
The Growth Mindset: Explanations and ActivitiesThe Growth Mindset: Explanations and Activities
The Growth Mindset: Explanations and Activities
Damian T. Gordon
 
Hyperparameter Tuning in Neural Networks
Hyperparameter Tuning in Neural NetworksHyperparameter Tuning in Neural Networks
Hyperparameter Tuning in Neural Networks
Damian T. Gordon
 
Early 20th Century Modern Art: Movements and Artists
Early 20th Century Modern Art: Movements and ArtistsEarly 20th Century Modern Art: Movements and Artists
Early 20th Century Modern Art: Movements and Artists
Damian T. Gordon
 
An Introduction to Generative Artificial Intelligence
An Introduction to Generative Artificial IntelligenceAn Introduction to Generative Artificial Intelligence
An Introduction to Generative Artificial Intelligence
Damian T. Gordon
 
An Introduction to Green Computing with a fun quiz.
An Introduction to Green Computing with a fun quiz.An Introduction to Green Computing with a fun quiz.
An Introduction to Green Computing with a fun quiz.
Damian T. Gordon
 
Introduction to Prompts and Prompt Engineering
Introduction to Prompts and Prompt EngineeringIntroduction to Prompts and Prompt Engineering
Introduction to Prompts and Prompt Engineering
Damian T. Gordon
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
TRIZ: Theory of Inventive Problem Solving
TRIZ: Theory of Inventive Problem SolvingTRIZ: Theory of Inventive Problem Solving
TRIZ: Theory of Inventive Problem Solving
Damian T. Gordon
 
Some Ethical Considerations of AI and GenAI
Some Ethical Considerations of AI and GenAISome Ethical Considerations of AI and GenAI
Some Ethical Considerations of AI and GenAI
Damian T. Gordon
 
Some Common Errors that Generative AI Produces
Some Common Errors that Generative AI ProducesSome Common Errors that Generative AI Produces
Some Common Errors that Generative AI Produces
Damian T. Gordon
 
The Use of Data and Datasets in Data Science
The Use of Data and Datasets in Data ScienceThe Use of Data and Datasets in Data Science
The Use of Data and Datasets in Data Science
Damian T. Gordon
 
A History of Different Versions of Microsoft Windows
A History of Different Versions of Microsoft WindowsA History of Different Versions of Microsoft Windows
A History of Different Versions of Microsoft Windows
Damian T. Gordon
 
Writing an Abstract: A Question-based Approach
Writing an Abstract: A Question-based ApproachWriting an Abstract: A Question-based Approach
Writing an Abstract: A Question-based Approach
Damian T. Gordon
 
Using GenAI for Universal Design for Learning
Using GenAI for Universal Design for LearningUsing GenAI for Universal Design for Learning
Using GenAI for Universal Design for Learning
Damian T. Gordon
 
A CheckSheet for Inclusive Software Design
A CheckSheet for Inclusive Software DesignA CheckSheet for Inclusive Software Design
A CheckSheet for Inclusive Software Design
Damian T. Gordon
 
A History of Versions of the Apple MacOS
A History of Versions of the Apple MacOSA History of Versions of the Apple MacOS
A History of Versions of the Apple MacOS
Damian T. Gordon
 
68 Ways that Data Science and AI can help address the UN Sustainability Goals
68 Ways that Data Science and AI can help address the UN Sustainability Goals68 Ways that Data Science and AI can help address the UN Sustainability Goals
68 Ways that Data Science and AI can help address the UN Sustainability Goals
Damian T. Gordon
 
Copyright and Creative Commons Considerations
Copyright and Creative Commons ConsiderationsCopyright and Creative Commons Considerations
Copyright and Creative Commons Considerations
Damian T. Gordon
 
Exam Preparation: Some Ideas and Suggestions
Exam Preparation: Some Ideas and SuggestionsExam Preparation: Some Ideas and Suggestions
Exam Preparation: Some Ideas and Suggestions
Damian T. Gordon
 
Studying and Notetaking: Some Suggestions
Studying and Notetaking: Some SuggestionsStudying and Notetaking: Some Suggestions
Studying and Notetaking: Some Suggestions
Damian T. Gordon
 
The Growth Mindset: Explanations and Activities
The Growth Mindset: Explanations and ActivitiesThe Growth Mindset: Explanations and Activities
The Growth Mindset: Explanations and Activities
Damian T. Gordon
 
Hyperparameter Tuning in Neural Networks
Hyperparameter Tuning in Neural NetworksHyperparameter Tuning in Neural Networks
Hyperparameter Tuning in Neural Networks
Damian T. Gordon
 
Early 20th Century Modern Art: Movements and Artists
Early 20th Century Modern Art: Movements and ArtistsEarly 20th Century Modern Art: Movements and Artists
Early 20th Century Modern Art: Movements and Artists
Damian T. Gordon
 
An Introduction to Generative Artificial Intelligence
An Introduction to Generative Artificial IntelligenceAn Introduction to Generative Artificial Intelligence
An Introduction to Generative Artificial Intelligence
Damian T. Gordon
 
An Introduction to Green Computing with a fun quiz.
An Introduction to Green Computing with a fun quiz.An Introduction to Green Computing with a fun quiz.
An Introduction to Green Computing with a fun quiz.
Damian T. Gordon
 

Recently uploaded (20)

Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
National Information Standards Organization (NISO)
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 

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", "[email protected]") c2 = Contact("Fred StaffMember", "[email protected]") s1 = Supplier("Joe Supplier", "[email protected]") s2 = Supplier("John Supplier", "[email protected]")
  • 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", "[email protected]") c2 = Contact("Fred StaffMember", "[email protected]") c3 = Contact("Anne StaffMember", "[email protected]") 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", "[email protected]") c2 = Contact("Fred StaffMember", "[email protected]") c3 = Contact("Anne StaffMember", "[email protected]") 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", "[email protected]") s2 = Supplier("John Supplier", "[email protected]") s3 = SupplierCheck("Anne Supplier", "[email protected]") s4 = SupplierCheck("Mary Supplier", "[email protected]")
  • 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.