Inheritance
Inheritance lets a new class build on an existing one. The new class (the child or subclass) gets everything from the parent (base class), and can add or change behaviour.
Python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
def introduce(self):
return f"I'm {self.name} and I say {self.speak()}"
class Dog(Animal): # Dog inherits from Animal
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
for pet in [Dog("Rex"), Cat("Luna"), Animal("Mystery")]:
print(pet.introduce())Dog and Cat never define __init__ or introduce; they inherit them. They override speak with their own version.
super(): extending the parent
To add to a parent's method rather than replace it, call the parent's version with super():
Python
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def describe(self):
return f"{self.name} earns {self.salary:,}"
class Manager(Employee):
def __init__(self, name, salary, team_size):
super().__init__(name, salary) # let Employee set name and salary
self.team_size = team_size
def describe(self):
return super().describe() + f" and leads {self.team_size} people"
print(Employee("Ada", 138000).describe())
print(Manager("Grace", 210000, 12).describe())isinstance and issubclass
Python
class Animal: pass
class Dog(Animal): pass
rex = Dog()
print(isinstance(rex, Dog)) # True
print(isinstance(rex, Animal)) # True: a Dog IS an Animal
print(issubclass(Dog, Animal))
print(isinstance(42, (int, float)))Polymorphism
Code that works with the parent type works with every child, each behaving in its own way. This is polymorphism:
Python
class Shape:
def area(self):
raise NotImplementedError
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return 3.14159 * self.r ** 2
class Square(Shape):
def __init__(self, s): self.s = s
def area(self): return self.s ** 2
shapes = [Circle(1), Square(3), Circle(2.5)]
print(round(sum(s.area() for s in shapes), 2))The loop doesn't care which kind of shape each one is; it just calls area().
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.