What You Will Learn
Intermediate
- How inheritance works
- Overriding parent methods
- Using super() to call parent
Terminalpython
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Buddy says Woof!
print(cat.speak()) # Whiskers says Meow!Using super()
Terminalpython
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age) # Call parent __init__
self.breed = breed
def info(self):
return f"{self.name}, {self.age} years, {self.breed}"
dog = Dog("Buddy", 3, "Labrador")
print(dog.info()) # Buddy, 3 years, LabradorPractical Exercise
Create class Animal with speak()
Create Dog(Animal) that overrides speak()
Create Cat(Animal) that overrides speak()
Use super().__init__() to call parent constructor
Test: dog.speak(), cat.speak()
Key Takeaways
- Inheritance: ChildClass(ParentClass).
- Child inherits all attributes and methods from parent.
- Override: redefine a method in child with same name.
- super() calls parent methods. Use super().__init__() in constructors.
- Promotes code reuse.
Comments
Comments
Post a Comment