class Student:
# this is a class-level variable
# instead of each instance having its own copy
# the variable is shared among all `Student`
next_id_counter = 1
def __init__(self, name):
# assign each student a unique id
# note use of Student. not self.
self.id = Student.next_id_counter
Student.next_id_counter += 1
self.name = name
self.year = 1
self.major = "Undeclared"
self.course_grades = {}
self.extracurriculars = []
def add_grade(self, course_name, grade):
self.course_grades[course_name] = grade
@property
def gpa(self):
grade_pts = {"A":4.0, "A-":3.7, "B+":3.3, "B":3.0, "B-":2.7, "C+":2.3, "C":2.0, "C-":1.7, "D+":1.3, "D":1.0, "F":0.0}
if len(self.course_grades) == 0:
return 0
return sum(grade_pts[g] for g in self.course_grades.values()) / len(self.course_grades)
def __repr__(self):
return f"Student(name={self.name}, id={self.id}, gpa={self.gpa})"27 Inheritance
Goals
- Introduce inheritance and its implementation in Python.
- Explore the idea of the interface.
- See how abstract base classes allow us to separate interface from implementation.
Motivations
Let’s say we’re building an application that tracks students.
s1 = Student("Adam")
s2 = Student("Beth")
s2.add_grade("Programming Python", "A")
s2.add_grade("Discrete Math", "B+")print(s1)
print(s2)Student(name=Adam, id=1, gpa=0)
Student(name=Beth, id=2, gpa=3.65)
Perhaps we want to add Alum to our application.
An alum will have some things in common with students:
- They still have a name.
- We want to remember their major.
- We’ll still want to keep track of their grades/GPA.
We now also:
- Want to record their year of graduation.
- No longer want to allow grades to be recorded.
- Want to be able to calculate how long ago they graduated.
- When displaying them, we want to display their graduation year.
How to implement?
We could copy student.py and rename to alum.py and rename the class as needed.
But copying & pasting is generally a bad idea!
We’d need to fix bugs & add features in both classes separately.
A new feature in Student would need to be copied over to Alum, this will quickly get messy.
Inheritance in Python
Instead we will use inheritance, which allows us to create a new class from an existing one. The new class inherits the attributes and methods from the parent.
- superclass, parent, or base class: The pre-existing class.
- subclass, child, or derived class: The new class that inherits the code (attributes & methods) of another class.
Subclasses can extend/modify the functionality of superclasses.
Syntax:
class Subclass(Superclass):
passFor example:
class Alum(Student):
passAt this point, Alum is a new class with the exact same implementation as Student.
Typically we’ll want to add new instance & class variables, methods, etc.
Newly defined features will only apply to instances of Alum
It is possible to override parent class behavior, or rely on parent behavior, whichever is needed.
Adding & Overriding Behavior
class Alum(Student):
def __init__(self, name, grad_year):
# call Student's constructor, which contains id logic
super().__init__(name)
self.graduation_year = grad_year
# new behavior
def years_since_graduation(self, now):
return now - self.graduation_year
# overrides parent's add_grade
def add_grade(self, course_name, grade):
raise NotImplementedError("cannot add grades to Alum")
#print("Sorry, you cannot add grades to Alums")
# we choose not call super().add_grade here
# overrides parent's __repr__
def __repr__(self):
#return f"Alum(name={self.name}, id={self.id}, gpa={self.gpa}, graduated={self.graduation_year})"
string = super().__repr__()
string += " is an alum"
return stringalum1 = Alum("Charlie", 2016)
print(alum1)
print(alum1.years_since_graduation(2022), "years since graduation")
#alum1.add_grade("Python", "B")
alum1.gpaStudent(name=Charlie, id=3, gpa=0) is an alum
6 years since graduation
0
alum2 = Alum("Charlie", 2016)super()
Allows direct access to parent class(es).
Many different ways to be called, but for our purposes we will stick to super().method_name() to access parent implementation of method_name()
issubclass & isinstance
isinstance(object, class_type)- Check if an object is of an instance.issubclass(class_type, class_type2)- Check if a type is a subclass of another type.
isinstance(7, int)True
# same as?
type(7) == intTrue
type(7) == objectFalse
isinstance(7, object)True
# isinstance checks the inheritance hierarchy
isinstance(alum2, object)True
type(alum2) == StudentFalse
isinstance([1, 2, 3], list)True
s1 = Student("Sarah")
isinstance(s1, Student)True
# child classes are instances of parent types
alum1 = Alum("Charlie", 2016)
isinstance(alum1, Student)True
# but not vice-versa
isinstance(s1, Alum)False
# INCORRECT: issubclass takes class names, not instances
issubclass(alum1, Student)
# Instead
issubclass(Alum, Student)object
Every object derives from a base class named object.
class Point:
def __init__(self, x, y):
self.x = y
# Same as:
class Point(object):
def __init__(self, x, y):
self.x = y
self.y = yWhen to Use Inheritance
As a general rule, inheritance should be thought of as implementing an “is-a” relationship between child and parent.
If it makes sense to say “Y is an X”, then we might create a relationship where Y is a child class of X.
This is because a child class shares all methods and attributes of the parents.
- Student is a (specialized type of) Person
- Alum is a (specialized type of) Student
This can apply to real-world entities like these, or abstract concepts like data structures.
For example, we could define a SortedList type that ensures its elements are always sorted. This is a specialization of list, it would be correct to say SortedList(list) and base our implementation on the built in list.
Method Resolution Order
When we call a function, Python walks up the chain of parent classes to determine the first one that has the method defined.
This is called the method resolution order.
help(Alum)Help on class Alum in module __main__:
class Alum(Student)
| Alum(name, grad_year)
|
| Method resolution order:
| Alum
| Student
| builtins.object
|
| Methods defined here:
|
| __init__(self, name, grad_year)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| add_grade(self, course_name, grade)
| # overrides parent's add_grade
|
| years_since_graduation(self, now)
| # new behavior
|
| ----------------------------------------------------------------------
| Readonly properties inherited from Student:
|
| gpa
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Student:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Student:
|
| next_id_counter = 7
Alum.__mro__(__main__.Alum, __main__.Student, object)
help(super)Help on class super in module builtins:
class super(object)
| super() -> same as super(__class__, <first argument>)
| super(type) -> unbound super object
| super(type, obj) -> bound super object; requires isinstance(obj, type)
| super(type, type2) -> bound super object; requires issubclass(type2, type)
| Typical use to call a cooperative superclass method:
| class C(B):
| def meth(self, arg):
| super().meth(arg)
| This works for class methods too:
| class C(B):
| @classmethod
| def cmeth(cls, arg):
| super().cmeth(arg)
|
| Methods defined here:
|
| __get__(self, instance, owner=None, /)
| Return an attribute of instance, which is of type owner.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __self__
| the instance invoking super(); may be None
|
| __self_class__
| the type of the instance invoking super(); may be None
|
| __thisclass__
| the class invoking super()
Interfaces
The collection of dunder methods for various types define interfaces. We saw that we can say that a type is a sequence if it implements a specific set of dunder methods.
An interface is the “exposed” means of interacting with a system.
When you get into a car, there’s an interface for starting the engine, controlling the direction, speed, etc. There are of course, other ways to start and stop a car– but we generally prefer to use the pedals.
The same is true of our code. When we write functions and classes meant to be used by other developers (or other parts of our own code) we are creating interfaces. We often think of interfaces as a contract between the author and the user of the interface.
Benefits of Interfaces
Using interfaces helps with many common challenges in larger programs:
- Allow multiple team members to work on related code without requiring one portion to be 100% complete before the other starts. As seen in the next example
- Clear separation of interface and implementation allows for safe refactoring of code, you can know when your change is likely to break something elsewhere in the program.
- The interface is typically the right level of abstraction for testing, so a good interface can help define tests.
- A well-written interface can make it possible to change implementations (e.g. switch which database is being used) without disruptive changes throughout the entire codebase.
Example: Student Interface
Two developers, José and Sally, are working together on a project.
José is responsible for defining the class definitions of the type of people. For example:
from datetime import dateclass Student:
def __init__(self, first_name, last_name, birth_date):
self.first_name = first_name
self.last_name = last_name
self.birth_date = birth_date
def age(self):
today = date.today()
age = today.year - self.birth_date.year - ((today.month, today.day) < (self.birth_date.month, self.birth_date.day))
return str(age)
students = [Student("Ada", "Lovelace", date(2000, 12, 10)),
Student("Charles", "Babbage", date(1991, 12, 26))]Sarah’s job is to define a function that displays the full names and ages of people. She starts with a function like:
def display_people(people):
for person in people:
print(f"{person.first_name} {person.last_name} is {person.age()} years old.")
display_people(students)Ada Lovelace is 25 years old.
Charles Babbage is 34 years old.
José then reads Falsehoods Programmers Believe About Names and decides that he wants to change the implementation to store the name as a tuple of first and last names.
class Student:
def __init__(self, first_name, last_name, birth_date):
# for now we'll leave the constructor the same and just combine the two
self.names = (first_name, last_name)
self.birth_date = birth_date
def age(self):
today = date.today()
age = today.year - self.birth_date.year - ((today.month, today.day) < (self.birth_date.month, self.birth_date.day))
return str(age)try:
students = [Student("Ada", "Lovelace", date(2000, 12, 10)),
Student("Charles", "Babbage", date(1991, 12, 26))]
display_people(students)
except Exception as e:
print(e)'Student' object has no attribute 'first_name'
Sarah’s code breaks because she’s accessing the first_name and last_name attributes directly. She could fix it by accessing the names attribute and then indexing into it, but that’s not very readable, and it is not very future-proof.
Instead, she asks José to define an interface for accessing the name. He does so by defining a full_name method:
class Student:
def __init__(self, first_name, last_name, birth_date):
# for now we'll leave the constructor the same and just combine the two
self.names = (first_name, last_name)
self.birth_date = birth_date
def full_name(self):
return f"{self.names[0]} {self.names[1]}"
def age(self):
today = date.today()
age = today.year - self.birth_date.year - ((today.month, today.day) < (self.birth_date.month, self.birth_date.day))
return str(age)and updates her function to use it:
def display_people(people):
for person in people:
print(f"{person.full_name()} is {person.age()} years old.")students = [Student("Ada", "Lovelace", date(2000, 12, 10)),
Student("Charles", "Babbage", date(1991, 12, 26))]
display_people(students)Ada Lovelace is 25 years old.
Charles Babbage is 34 years old.
Now, if José decides to change the implementation of the name, Sarah’s code won’t break since they’ve agreed on an interface.
A new team member, Pat, is tasked with writing an Employee class.
class Employee:
def __init__(self, first_name, last_name, age, employee_id):
self.names = (first_name, last_name)
self.age = age
self.employee_id = employee_id
def name(self):
return f"{self.names[0]} {self.names[1]}"# Sarah is asked to ensure display_people will work for Employee as well
try:
employees = [Employee("Fred", "Flintstone", 44, 1),
Employee("George", "Jetson", 40, 7777)]
display_people(employees)
except Exception as e:
print(e)'Employee' object has no attribute 'full_name'
Sarah’s display_people function does not work with Employee objects because it is expecting a full_name method but Employee has a name method. Additionally, age is a property of Employee but a method on Student.
A naive solution to this might be to add more code to display_people to check what type it gets. Why is this not a good idea?
This problem stems from the fact that the code the three are writing is already tightly coupled. This means that the code is dependent on the implementation details of other parts of the code. In this case, the display_people function is dependent on the full_name method and the age method.
To loosely couple the code, we need to define an interface that the display_people function can depend on, rather than the implementation details of the Student and Employee classes.
Abstract Base Classes
One solution to this problem is to define an interface using an abstract class, that defines the methods that must be implemented by any class that implements the interface.
In Python, we can use the abc module to define abstract classes. A class that inherits from ABC is an abstract class, and any methods decorated with @abstractmethod must be implemented by any class that inherits from it.
For example:
from abc import ABC, abstractmethod
class Person(ABC):
@abstractmethod
def full_name(self):
pass
@abstractmethod
def age(self):
pass
try:
p = Person()
except Exception as e:
print(e)Can't instantiate abstract class Person without an implementation for abstract methods 'age', 'full_name'
Person is an abstract base class (ABC), and any class that inherits from it must implement the full_name and age methods. Trying to instantiate Person directly, or any incomplete subclass, will raise an error.
To make a class that implements the Person interface, we can do:
class Student(Person):
def __init__(self, first_name, last_name, birth_date):
self.names = (first_name, last_name)
self.birth_date = birth_date
def full_name(self):
return f"{self.names[0]} {self.names[1]}"
def age(self):
today = date.today()
age = today.year - self.birth_date.year - ((today.month, today.day) < (self.birth_date.month, self.birth_date.day))
return str(age)
class Employee(Person):
def __init__(self, first_name, last_name, age, employee_id):
self._names = (first_name, last_name)
self._age = age
self.employee_id = employee_id
def full_name(self):
return f"{self._names[0]} {self._names[1]}"
def age(self):
return str(self._age)Sarah’s implementation of display_people will work with any Person subclass, since they are guaranteed to have the required methods.
students = [Student("Ada", "Lovelace", date(2000, 12, 10)),
Student("Charles", "Babbage", date(1991, 12, 26))]
employees = [Employee("Fred", "Flintstone", 44, 1),
Employee("George", "Jetson", 40, 77777)]
people = students + employees
display_people(people)Ada Lovelace is 25 years old.
Charles Babbage is 34 years old.
Fred Flintstone is 44 years old.
George Jetson is 40 years old.
It is also possible to provide default implementations in classes. These can be overridden by subclasses.
For example:
from abc import ABC, abstractmethod
class Person(ABC):
def __init__(self, first_name, last_name, birth_date):
self.names = (first_name, last_name)
self.birth_date = birth_date
# these methods will be inherited by subclasses, but can be overridden
def full_name(self):
return f"{self.names[0]} {self.names[1]}"
def age(self):
today = date.today()
age = today.year - self.birth_date.year - ((today.month, today.day) < (self.birth_date.month, self.birth_date.day))
return str(age)
@abstractmethod
def include_in_payroll(self):
pass
class Student(Person):
def __init__(self, first_name, last_name, birth_date):
# if you need to call a parent classes implementation, you can use super()
super().__init__(first_name, last_name, birth_date)
def include_in_payroll(self):
return False
class Employee(Person):
def __init__(self, first_name, last_name, birth_date, employee_id):
super().__init__(first_name, last_name, birth_date)
self.employee_id = employee_id
def include_in_payroll(self):
return True