Level: Intermediate | Prerequisite: Week 7
Learning Goals
- Use class inheritance and
super() - Demonstrate polymorphism in code
- Override magic methods (
__str__,__eq__,__add__, etc.) - Distinguish between class methods and static methods
1. Inheritance
Inherit attributes and methods from a parent class.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal): #Animal Inheritance
def speak(self): #Method Overriding
return "Woof Woof"
d = Dog("Badugi")
print(d.name, d.speak()) #Badugi Woof Woof
2. super()
Call the parent's methods.
class Puppy(Dog):
def __init__(self, name, age):
super().__init__(name) #Call parent __init__
self.age = age
3. Polymorphism
Implement the same method name differently in various classes. The caller does not care about the type.
animals = [Dog("Badugi"), Cat("Butterfly"), Cow("Spotty")]
for a in animals:
print(a.speak()) #Woof woof / Meow / Moo
4. Magic Methods
Special methods whose names start and end with __xxx__. They are connected to Python syntax.
| Method | Trigger |
|---|---|
__str__ |
str(x), print(x) |
__repr__ |
Displayed in REPL, repr(x) |
__len__ |
len(x) |
__eq__ |
x == y |
__add__ |
x + y |
__getitem__ |
x[i] |
__iter__ / __next__ |
for ... in x |
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
p = Point(1, 2) + Point(3, 4)
print(p) # Point(4, 6)
print(p == Point(4, 6)) # True
5. classmethod / staticmethod
class Date:
def __init__(self, y, m, d):
self.y, self.m, self.d = y, m, d
@classmethod
def from_string(cls, s):
y, m, d = map(int, s.split("-"))
return cls(y, m, d) #Create Instance
@staticmethod
def is_valid(y, m, d):
return 1 <= m <= 12 and 1 <= d <= 31
print(Date.from_string("2026-05-09").y)
print(Date.is_valid(2026, 5, 9))
Key Examples (examples/)
| File | Content |
|---|---|
01_inherit.py |
Inheritance and super |
02_polymorphism.py |
Polymorphism |
03_magic.py |
Magic methods |
04_classmethod.py |
classmethod/staticmethod |
⚠️ Common Mistakes
- Missing
super().__init__()— Parent attributes are not initialized. - Calling magic methods normally — Not
p.add(q)butp + q. - Only creating
__eq__and omitting__hash__— Cannot be used as set/dict keys.__hash__should also be defined consistently. - Overusing multiple inheritance — Possible but complicated. Prefer composition if possible.
❓ FAQ
Q1. How to create an abstract class (interface)?
A. Use abc.ABC and @abstractmethod.
Q2. __str__ vs __repr__ ?
A. __str__ is for humans, __repr__ is for developers (debugging). Usually, defining __repr__ alone is enough.
Q3. Inheritance vs Composition? A. Use inheritance for 'is-a' relationships, and composition when 'has-a' applies (owning attributes). If unsure, use composition.
📝 Exercises (exercises/)
exercise1.md—Shapeabstract →Rectangle,Circleexercise2.md—Playlistclass + magic methodsexercise3.md—Vectorclass (+, -, ==, repr)
Next Week
Week 9. Regular Expressions