Inheritance & Special Methods
class Animal:
def speak(self): return "..."
def eat(self): return "nom"
class Dog(Animal):
def speak(self): return "woof"Dog(Animal) means a Dog gets everything an Animal has, and can add or change things.
1Level 1 · BasicsBasics
Often one kind of thing is a special version of another: a student is a person, a savings account is a bank account. Inheritance lets a new class reuse everything from an existing class and add or change only what's different. This lesson also covers special methods, which make your objects work with print(), len(), + and ==.
Inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal): # Dog inherits from Animal
def speak(self): # override: replace the parent's version
return "Woof!"
Dog(Animal) means Dog is a child (subclass) of Animal, the parent. Dog gets __init__ and name for free, and replaces speak with its own version. This is called overriding.
super(): reuse the parent's code
When the child needs extra setup, call the parent's version with super() and then add to it:
class Student(Person):
def __init__(self, name, age, dept):
super().__init__(name, age) # let Person set name and age
self.dept = dept # then add the new part
Polymorphism
Different classes can have methods with the same name. A loop can call animal.speak() on a Dog, a Cat or a Cow without caring which one it is, and each answers in its own way. isinstance(obj, Animal) checks whether an object is an Animal (or a child of one).
Special ("dunder") methods
Methods with double underscores on both sides let your objects work with Python's built-in syntax:
| Method | Used by |
|---|---|
__str__(self) | print(obj) and str(obj): a friendly description |
__repr__(self) | the developer view, shown in lists and the console |
__len__(self) | len(obj) |
__eq__(self, other) | obj == other |
__add__(self, other) | obj + other |
__lt__(self, other) | obj < other, and so sorted() |
Dataclasses: less typing
For classes that mainly hold data, @dataclass writes __init__, __repr__ and __eq__ for you, based on the fields you list.
Key points:class Child(Parent)inherits; override a method by redefining it;super()calls the parent's version; dunder methods hook into print, len, +, == and sorting;@dataclasssaves boilerplate.
See it in actionThe child class overrides a method
Dog gets __init__ from Animal but uses its own speak().
Try it yourselfExample 1: Inheritance and overriding
Each animal shares __init__ from Animal but speaks in its own way.
Output appears hereA Cat is an Animal
Fill the blanks so Cat inherits from Animal and overrides sound(), printing Meow.
class Animal: def sound(self): return "..." class Cat(): def (self): return "Meow" print(Cat().sound())
Shapes with area
Make a base class Shape with area() returning 0, and subclasses Square(side) and Circle(r). Print the area of a Square of side 3 and of a Circle of radius 1 rounded to 2 places: 9 3.14.
Example 2: super() for extra setup
Student reuses Person's setup, then adds its own attribute and method.
Output appears hereForgot to call super()
Student should keep the name set up by Person and print Mim 8, but it crashes. Fix Student.__init__.
Example 3: Special methods
__str__, __add__, __eq__ and __len__ make Vector objects feel built in.
Output appears hereA nice printout
Fill the blank so printing a Book shows Dune by Herbert.
class Book: def __init__(self, title, author): self.title, self.author = title, author def (self): return f"{self.title} by {self.author}" print(Book("Dune", "Herbert"))
Example 4: Dataclasses and sorting
@dataclass writes __init__ and __repr__; order=True adds comparisons so sorted() works.
Output appears hereSort with __lt__
Give Card a __lt__ method that compares by value, so sorted() works. Print the sorted values of cards 7, 2, 9: [2, 7, 9].
2Level 2 · IntermediateAbstract classes and more special methods
Abstract base classes
from abc import ABC, abstractmethod. A class with an @abstractmethod can't be created directly; every child must implement the method. This is how you define a "shape contract": every shape has an area().
Operator overloading
__add__ makes a + b work, __lt__ makes sorting work, __len__ answers len(), __getitem__ allows obj[i], and __contains__ answers in.
isinstance and duck typing
isinstance(x, Shape) checks the family tree. But Python usually prefers duck typing: if an object has the method you need, just call it.
See it in actionWhich method runs?
Watch Python look up speak() on each object's own class first.
Example 5: Shapes with an abstract base class
Shape() can't be created, and every shape sorts by area thanks to __lt__.
Output appears hereExample 6: A playlist that acts like a list
len, indexing, in and + all work because of special methods.
Output appears here3Level 3 · AdvancedMultiple inheritance, MRO and mixins
Method resolution order
With several parents, Python searches classes in a fixed order called the MRO (Class.__mro__). super() calls the next class in the MRO, not simply "the parent", which is how cooperative classes all get a turn.
Mixins
A mixin is a small class that adds one ability (logging, JSON export, comparison) and is meant to be combined with others: class Student(JsonMixin, Person).
Dataclasses go further
@dataclass(order=True, frozen=True) generates comparison methods and makes objects read-only; field(default_factory=list) avoids the shared-default trap.
When not to inherit
If the child doesn't truly pass every test the parent would ("a Square is a Rectangle" breaks when you change width alone), use composition.
Example 7: super() follows the MRO
Each class adds its part and passes on to the next one in the MRO.
Output appears hereExample 8: A mixin and a frozen, ordered dataclass
to_json comes from the mixin; sorting and read-only come from the dataclass.
Output appears hereWhat does this print?
class A:
def hi(self):
return "A"
class B(A):
def hi(self):
return "B" + super().hi()
print(B().hi())50 graded problems are waiting in Topic Practice.