Inheritance allows a “child” class, to inherit properties and methods from a “parent” class in source. It’s a way to share code between classes. For example, say we have this Aircraft class:
class Aircraft:
def __init__(self, height: int, speed: int) -> None:
self.height = height
self.speed = speed
def fly_up(self) -> None:
self.height += self.speedAnd say we want to also model more specific kinds of aircraft. We could create a more specific Helicopter class like this:
class Helicopter:
def __init__(self, height: int, speed: int) -> None:
self.height = height
self.speed = speed
self.direction = 0
def fly_up(self) -> None:
self.height += self.speed
def rotate(self) -> None:
self.direction += 90Trouble is, we’ve rewritten a lot of the same code twice… wouldn’t it be nice if a Helicopter could just take all the behavior from an Aircraft, and then just add its own unique behavior on top of that? Well, it can! We’ll just make Helicopter a child class of Aircraft:
class Helicopter(Aircraft):
def __init__(self, height: int, speed: int) -> None:
super().__init__(height, speed)
self.direction = 0
def rotate(self) -> None:
self.direction += 90By adding Aircraft in parentheses after Helicopter, we’re saying “make Helicopter a child class of Aircraft”. Now Helicopter inherits all the properties and methods of Aircraft!
The super() function returns a proxy of the parent class, meaning we can use it to call the parent class’s constructor and other methods. So the Helicopter’s constructor says “first, call the Aircraft constructor, and then additionally set the direction property”.
Now, say we want to create a Jet class. Again, because all jets are aircraft, we can inherit from Aircraft again. One parent class can have as many child classes as you want.
class Jet(Aircraft):
def __init__(self, speed: int) -> None:
# Jets always start on the ground
super().__init__(0, speed)
def go_supersonic(self) -> None:
self.speed *= 2When to Inherit
When a child class inherits from a parent, it inherits everything. If you only want to share some functionality, inheritance should not be the tool you use. Just share some functions, or maybe make a new parent class that both classes can inherit from.