Basic Inheritance Damian Gordon.

Slides:



Advertisements
Similar presentations
More on Classes Inheritance and Polymorphism
Advertisements

Python Objects and Classes
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
Basics of Inheritance CS 5010 Program Design Paradigms "Bootcamp" Lesson 12.1 © Mitchell Wand, This work is licensed under a Creative Commons.
Week 8 Recap CSE 115 Spring Composite Revisited Once we create a composite object, it can itself refer to composites. Once we create a composite.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Object-oriented Programming Concepts
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Object Oriented Software Development
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Object Oriented Software Development
Ruby Objects, Classes and Variables CS 480/680 – Comparative Languages.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
Java Programming Fifth Edition Chapter 9 Introduction to Inheritance.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
EKT472: Object Oriented Programming Overloading and Overriding Method.
Object-Orientated Design (Summary)
Ruby Inheritance and other languages….
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Inheritance.
Sections Inheritance and Abstract Classes
Lecture 14 Throwing Custom Exceptions
COMPSCI 107 Computer Science Fundamentals
Overriding Method.
Modules and Packages Damian Gordon.
Adapted from slides by Marty Stepp and Stuart Reges
Final and Abstract Classes
CS-104 Final Exam Review Victor Norman.
Week 4 Object-Oriented Programming (1): Inheritance
Object Oriented Programming in Python
Object Oriented Programming
Object-oriented programming
Creating and Deleting Instances Access to Attributes and Methods
Designing for Inheritance
Object-oriented programming
Object Oriented Programming (OOP) LAB # 8
The super Reference Constructors cannot be used in child classes, even though they have public visibility Yet we often want to use the parent's constructor.
Functions BIS1523 – Lecture 17.
Java Programming Language
Recursion 2-Dec-18.
Interfaces.
Programming paradigms
Advanced Java Programming
Multiple Inheritance Damian Gordon.
Java – Inheritance.
Inheritance Inheritance is a fundamental Object Oriented concept
An Introduction to Object Orientated Programming
Java Programming, Second Edition
Java Inheritance.
BE MORE INVOLVED IN YOUR HEALTH CARE
Inheritance.
Inheritance and Polymorphism
Object Oriented Programming in A Level
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Java Programming Language
DEV-41: The Power of Polymorphism
CSE 231 Lab 11.
Prof. Katherine Gibson Prof. Jeremy Dixon
Final and Abstract Classes
Access Control Damian Gordon.
Programming For Big Data
Migrating to Object-Oriented Programs
References Revisted (Ch 5)
CMPE212 – Reminders Assignment 2 due next Friday.
Presentation transcript:

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 Because contacts_list is declared here, there is only one instance of this attribute , and it is accessed as Contacts.contact_list. class Contact: contacts_list = [] def _ _init_ _(self, name, email): self.name = name self.email = email Contact.contacts_list.append(self) # End Init # End Class

Append the newly instantiated Contact to the contacts_list. Basic Inheritance Because contacts_list is declared here, there is only one instance of this attribute , and it is accessed as Contacts.contact_list. class Contact: contacts_list = [] def _ _init_ _(self, name, email): self.name = name self.email = email Contact.contacts_list.append(self) # End Init # End Class Append the newly instantiated Contact to the contacts_list.

Basic Inheritance Contact name email contacts_list[ ] _ _init_ _( )

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 Create a new class called Supplier, that has all the methods and attributes of the Contact class. Now add a new method called order. class Supplier(Contact): def order(self, order): print(“The order will send ” “’{}’ order to ‘{}’”.format(order,self.name)) # End order. # End Class

Print out what was ordered from what supplier. Basic Inheritance Create a new class called Supplier, that has all the methods and attributes of the Contact class. Now add a new method called order. class Supplier(Contact): def order(self, order): print(“The order will send ” “’{}’ order to ‘{}’”.format(order,self.name)) # End order. # End Class Print out what was ordered from what supplier.

Basic Inheritance Contact name email contacts_list[ ] _ _init_ _( )

Supplier Basic Inheritance name email contacts_list[ ] _ _init_ _( ) 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'

Contact Supplier name name email email contacts_list[ ] _ _init_ _( ) _ _init_ _( ) 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

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.

Extending Built-Ins This is a new class that builds on the list type. 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 Instead of declaring contacts_list as a list we declare it as a class that inherits from list. 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 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: The new class inherits from the Supplier class. It is therefore a subclass of it. 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: The new class inherits from the Supplier class. It is therefore a subclass of it. 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 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.