C
Python/OOP/Lesson 18

Class Inheritance

45 min·theory
This chapter
2/3
Python

Class Inheritance

🎯 After reading this lesson

By the end of this lesson, you will be able to confidently do the following 3 things.

  • ✅ Single inheritance vs. multiple inheritance + MRO (Method Resolution Order)
  • ✅ When to use super()
  • ✅ Abstract classes (abc.ABC + @abstractmethod)

Keep these learning goals as a checklist — close the lesson once you can answer all of them.

Inheritance — Code + Output

class Child(Parent): = all of the parent's attributes and methods, plus additions and overrides by the child.


1. Basic Inheritance

python
class Animal:
    def __init__(self, name):
        self.name = name

    def introduce(self):
        print(f"I am {self.name}")

class Dog(Animal):    # Inherits Animal
    def bark(self):
        print("Woof woof!")

Bboppi = Dog("Bboppi")
Bboppi.introduce()           # I am Bboppi ← Parent method
Bboppi.bark()           # Woof woof!     ← Child method

2. Method Overriding

python
class Animal:
    def sound(self):
        print("???")

class Dog(Animal):
    def sound(self):                # Overrides parent method
        print("Woof woof!")

class Cat(Animal):
    def sound(self):
        print("Meow~")

animals = [Dog(), Cat()]
for a in animals:
    a.sound()
# Woof woof!
# Meow~

Same method name, different behavior = polymorphism.


3. super() — Calling the Parent Method

python
class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)         # Parent __init__ first
        self.breed = breed

Bboppi = Dog("Bboppi", "Poodle")
print(Bboppi.name, Bboppi.breed)            # Bboppi Poodle

4. isinstance — Checking Parent Types

python
Bboppi = Dog("Bboppi")
print(isinstance(Bboppi, Dog))       # True
print(isinstance(Bboppi, Animal))         # True (Parent is also OK)

5. Multiple Inheritance (Use with Care)

python
class CanSwim:
    def swim(self): print("Splash")

class CanFly:
    def fly(self): print("Soar")

class Duck(CanSwim, CanFly):    # Inherits both
    pass

d = Duck()
d.swim()      # Splash
d.fly()      # Soar

One-line Summary

class Child(Parent): + super().method() + method overriding = 90% of inheritance.

💻 Inheritance Example
# ============================================
# 📌 What this code does: Inherits common functionalities from a parent class
# 📌 Real-life analogy: Inheritance is like 'genetics'.
#    A Dog inherits characteristics from an Animal,
#    and adds its own unique characteristics (breed, bark).
# ============================================

# 🔹 Parent Class (Base Class): Defines common attributes and methods
class Animal:
    def __init__(self, name):
        self.name = name  # 🔹 Common attribute for all animals

    def speak(self):
        return "Makes a sound"  # 🔹 Default implementation (to be overridden in child classes)

# 🔹 Child Class: Declares inheritance by putting the parent class in parentheses
class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # 🔹 super(): Calls the parent class's __init__ (initializes name)
        self.breed = breed      # 🔹 Dog's unique additional attribute

    def speak(self):  # 🔹 Method Overriding: Redefines the parent's speak for Dog
        return "Woof!"

    def fetch(self):  # 🔹 Adds a new method unique to Dog (not in Animal)
        return f"{self.name} fetches the ball"

class Cat(Animal):
    def speak(self):  # 🔹 Cat also overrides speak
        return "Meow!"
    # 🔹 __init__ not defined → Parent's (Animal's) __init__ is used automatically

# 🔹 Usage
dog = Dog("Badugi", "Jindo Dog")
cat = Cat("Nabi")

print(dog.speak())   # ✅ Execution Result: Woof! (Overridden method)
print(cat.speak())   # ✅ Execution Result: Meow! (Overridden method)
print(dog.fetch())   # ✅ Execution Result: Badugi fetches the ball (Dog's unique method)
# ❌ cat.fetch() → AttributeError: Cat has no fetch method

# 🔹 Check Inheritance Relationship
print(isinstance(dog, Animal))  # ✅ Execution Result: True (Dog is an instance of Animal)
print(isinstance(dog, Dog))     # ✅ Execution Result: True
print(issubclass(Dog, Animal))  # ✅ Execution Result: True (Dog is a subclass of Animal)

💡 Key Points

1. Use class Child(Parent): syntax to inherit
2. Call parent methods with super()
3. Check relationships with isinstance() and issubclass()

Python's OOP defines objects using classes (class). __init__ is the constructor and self is a reference to the instance. Inheritance is implemented with class Child(Parent):, and parent methods are called with super(). Use @property for getters/setters, and @classmethod/@staticmethod for class and static methods. Multiple inheritance and MRO (Method Resolution Order) are also supported.

🐍 Try It Out — Class Inheritance

Run the concepts above as actual code. The fastest way to learn is to change the values yourself and see how things behave.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try asking AI like this

Once you understand the concepts in this lesson, you can give AI specific instructions. Not a vague 'fix this' — a request with vocabulary — that's where token savings start.

  • 'Convert this dict-based data structure to a dataclass'
  • 'Add appropriate __repr__ and __eq__ to this class'

Why does this reduce tokens?

When you don't know the concepts, even after getting an answer from AI you have to ask 'what does that mean?' again. That follow-up question is what eats tokens. Learn the concept once, and the conversation ends in one turn.

Inheritance - Python