Inheritance
A child class inherits attributes and methods from a parent class. Use super() to call the parent's methods.
Basic Inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof!"
d = Dog("Rex")
print(d.name, d.speak())
Try it Yourself →
Using super()
class Vehicle:
def __init__(self, brand):
self.brand = brand
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand)
self.model = model
def info(self):
return f"{self.brand} {self.model}"
c = Car("Toyota", "Corolla")
print(c.info())
Try it Yourself →
Multiple Inheritance
A class can inherit from more than one parent.
class Flyer:
def fly(self):
return "Flying"
class Swimmer:
def swim(self):
return "Swimming"
class Duck(Flyer, Swimmer):
pass
d = Duck()
print(d.fly())
print(d.swim())
Try it Yourself →