Single Inheritance
Inheritance lets a child class reuse and extend the behavior of a parent class. Use super() to call parent methods.
Basic Syntax
class Animal:
def __init__(self, name, sound):
self.name = name
self.sound = sound
def speak(self):
return f"{self.name} says {self.sound}!"
def describe(self):
return f"I am {self.name}"Child Class
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Woof") # call parent __init__
self.breed = breed
def fetch(self):
return f"{self.name} fetches the ball!"
class Cat(Animal):
def __init__(self, name, indoor=True):
super().__init__(name, "Meow")
self.indoor = indoorUsing the Classes
dog = Dog("Rex", "German Shepherd")
cat = Cat("Whiskers")
print(dog.speak()) # Rex says Woof! (inherited)
print(dog.fetch()) # Rex fetches the ball!
print(cat.describe()) # I am Whiskers (inherited)
print(isinstance(dog, Dog)) # True
print(isinstance(dog, Animal)) # True
print(issubclass(Dog, Animal)) # True