Python Inheritance
Inheritance lets a child class get methods and attributes from a parent class. The child class can add methods and change methods.
Inherit from a parent
Puppy starts as an empty child here. It still gets name and speak() from Dog.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return "Woof!"
class Puppy(Dog):
pass
pup = Puppy("Pip")
print(pup.name)
print(pup.speak())Reuse the parent setup
super() means the parent class. Its __init__ runs the parent setup first.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
class Puppy(Dog):
def __init__(self, name, age, toy):
super().__init__(name, age)
self.toy = toy
pup = Puppy("Pip", 1, "ball")
print(pup.name)
print(pup.age)
print(pup.toy)Add a new method
A child can have methods the parent does not have.
class Dog:
def __init__(self, name):
self.name = name
class Puppy(Dog):
def play(self):
return f"{self.name} plays."
pup = Puppy("Pip")
print(pup.play())Override a method
Use the same method name in the child. The child version wins for child objects.
class Dog:
def speak(self):
return "Woof!"
class Puppy(Dog):
def speak(self):
return "Yip!"
print(Dog().speak())
print(Puppy().speak())Check the family
isinstance() asks if an object belongs to a class family.
class Dog:
pass
class Puppy(Dog):
pass
pup = Puppy()
rex = Dog()
print(isinstance(pup, Puppy))
print(isinstance(pup, Dog))
print(isinstance(rex, Puppy))Example
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
return "Woof!"
class Puppy(Dog):
def __init__(self, name, age, toy):
super().__init__(name, age)
self.toy = toy
def speak(self):
return "Yip!"
def play(self):
return f"{self.name} plays with the {self.toy}."
rex = Dog("Rex", 5)
pip = Puppy("Pip", 1, "ball")
print(rex.speak())
print(pip.speak())
print(pip.play())
print(isinstance(pip, Dog))Key points
- Inheritance: a child class gets the methods and attributes of its parent class
- Parent class: the class another class starts from
- Child class: the new class that inherits from the parent
- Use class Child(Parent) to make a child class
- Use super().__init__() to run the parent setup code
- Use isinstance(obj, Class) to check an object's family
In this example, Dog stores name and age in __init__. Its speak() returns Woof!. Puppy calls super().__init__() to reuse that setup. Puppy then adds a toy of its own. Puppy overrides speak() so it returns Yip!. Puppy also adds play(), which Dog does not have. isinstance(pip, Dog) is True because Puppy inherits from Dog.
Note
A puppy is also a dog for isinstance().
A dog is not always a puppy.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does super().__init__(name, age) do in Puppy?