Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Module 5 - Object-Oriented Programming Python Python OOP Python Programming: From Zero to Real-World Applications

Inheritance - Extending Classes in Python

Reviewed & accurate
AI Summary

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, Labrador

Practical 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.
Previously: Lesson 32 covered methods.
Today: You learned: Child classes inherit from parent classes.
Next: Lesson 34 covers overriding.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments