Inheritance
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Inheritance lets you create a class based on another one: the child gets all of the parent's attributes and methods and can add its own or override existing ones.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal): # Dog inherits from Animal
def speak(self): # override the method
return f"{self.name}: Woof"
class Puppy(Dog):
def __init__(self, name, toy):
super().__init__(name) # call the parent's constructor
self.toy = toy
Puppy("Sharik", "ball").speak() # 'Sharik: Woof' — the method from Dog
super() gives you access to the parent class. Without super().__init__(name) the puppy wouldn't have a name attribute.
To check the relationship: isinstance(obj, Animal) returns True for both Dog and Puppy.
Inherit only when the child really is the parent ("a dog is an animal"). If an object simply contains another one ("a car has an engine"), store it as an attribute.
Task. From the Animal class, derive Dog (says Name: Woof) and Cat (says Name: Meow).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.