Sahaj.blogs
11 Oct 2023 · StudyPhase 1 · Python

Python · OOP: inheritance and dunder methods

Subclassing with super(), method overriding, and dunder methods (__repr__, __eq__, __len__, __add__) that plug objects into Python syntax.

Inheritance: class Child(Parent) reuses everything the parent has. The child can override methods and call the parent’s version through super().

Dunder (“double underscore”) methods are how objects hook into Python’s own syntax:

you writePython calls
repr(v) / in the REPL__repr__
str(v) / print(v)__str__
a == b__eq__
a + b__add__
len(v)__len__
import math

class Shape:
    def __init__(self, name):
        self.name = name
    def area(self):
        raise NotImplementedError
    def __repr__(self):
        return f"{type(self).__name__}({self.name!r}, area={self.area():.2f})"

class Circle(Shape):
    def __init__(self, r):
        super().__init__("circle")
        self.r = r
    def area(self):
        return math.pi * self.r ** 2

class Vec:
    def __init__(self, *xs): self.xs = xs
    def __add__(self, o):    return Vec(*(a + b for a, b in zip(self.xs, o.xs)))
    def __eq__(self, o):     return self.xs == o.xs
    def __len__(self):       return len(self.xs)
    def __repr__(self):      return f"Vec{self.xs}"

print(Circle(1))
print(isinstance(Circle(2), Shape))
v = Vec(1, 2, 3) + Vec(10, 20, 30)
print(v, len(v), v == Vec(11, 22, 33))

Output:

Circle('circle', area=3.14)
True
Vec(11, 22, 33) 3 True

#python#oop

Sources

  1. Inheritance — Python Software Foundation
  2. Data model: special method names — Python Software Foundation
  3. Built-in functions: super — Python Software Foundation