Class vs instance attributes. Mutable class attribute trap. MRO. staticmethod vs classmethod. Dunder methods. Python OOP is full of subtle traps.
class Counter: count = 0 # class attribute def __init__(self): Counter.count += 1 Counter() Counter() Counter() print(Counter.count)
count is a class attribute — shared among all instances. Each time an instance is created, Counter.count += 1 increments the shared counter. This is the classic pattern for counting instances. Accessing through the class name (Counter.count) makes the intent clear.class Dog: tricks = [] # mutable class attribute — danger! def add_trick(self, trick): self.tricks.append(trick) fido = Dog() rex = Dog() fido.add_trick("sit") rex.add_trick("shake") print(fido.tricks)
tricks is a class attribute — one list shared by ALL Dog instances. Both fido and rex append to the same list. Fix: move the list to __init__: self.tricks = []. This creates a separate list per instance.class A: x = 10 a = A() print(a.x) # reads class attribute a.x = 20 # creates instance attribute print(a.x) # reads instance attribute print(A.x) # class attribute unchanged
__dict__, then the class. a.x = 20 creates an instance attribute that shadows the class attribute. The class attribute A.x is untouched. The instance now has its own x.class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"Point({self.x}, {self.y})" def __repr__(self): return f"Point({self.x!r}, {self.y!r})" p = Point(1, 2) print(p) print(repr(p))
__str__ is called by print() and str() — human-readable output. __repr__ is called by repr() — developer-friendly, ideally valid Python to recreate the object. If __str__ is missing, Python falls back to __repr__.class Animal: def speak(self): return "..." class Dog(Animal): def speak(self): return "Woof" class Puppy(Dog): pass p = Puppy() print(p.speak()) print(isinstance(p, Animal))
Puppy doesn't define speak, so Python looks up to Dog which does. isinstance(p, Animal) is True because inheritance means Puppy IS-A Dog IS-A Animal.class A: def hello(self): return "A" class B(A): def hello(self): return "B" class C(A): def hello(self): return "C" class D(B, C): pass print(D().hello())
D.__mro__ is (D, B, C, A, object). Python searches left to right: D has no hello, B has it → "B" is returned. Python handles diamond inheritance correctly — no ambiguity errors, just a defined order.class Base: def __init__(self): print("Base init") class Child(Base): def __init__(self): super().__init__() print("Child init") Child()
super().__init__() calls the parent class's __init__ first. Without the super() call, Base.__init__ would never run. Order: Base initializes first (because super() is called first in Child's init), then Child continues. This is the correct pattern for cooperative inheritance.class MyClass: value = 42 @classmethod def class_method(cls): return cls.value @staticmethod def static_method(): return "no class or self" print(MyClass.class_method()) print(MyClass.static_method())
@classmethod: receives the class (cls) as the first argument — not an instance. Used for factory methods and class-level operations. @staticmethod: receives neither class nor instance — it's a plain function attached to the class namespace. Can be called on class or instance.class Circle: def __init__(self, radius): self.radius = radius @classmethod def from_diameter(cls, diameter): return cls(diameter / 2) c = Circle.from_diameter(10) print(c.radius)
@classmethod. cls(diameter/2) calls Circle(5.0), creating and returning a new instance. The cls parameter (not Circle) allows this to work correctly in subclasses too.class Box: def __init__(self, items): self.items = items def __len__(self): return len(self.items) def __contains__(self, item): return item in self.items b = Box([1, 2, 3]) print(len(b)) print(2 in b) print(bool(b))
__len__ makes len(b) work. __contains__ makes in work. bool(b) calls __bool__ if defined; if not, falls back to __len__ — since len > 0, bool is True.class Vector: def __init__(self, x, y): self.x, self.y = x, y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __str__(self): return f"({self.x}, {self.y})" v1 = Vector(1, 2) v2 = Vector(3, 4) print(v1 + v2)
__add__ defines what + does for your class. v1 + v2 calls v1.__add__(v2), which returns a new Vector(4, 6). print() calls __str__ on that. Operator overloading lets your objects behave like built-in types.class Temperature: def __init__(self, celsius): self._celsius = celsius @property def fahrenheit(self): return self._celsius * 9/5 + 32 t = Temperature(100) print(t.fahrenheit) print(type(Temperature.fahrenheit))
@property turns a method into a getter that looks like an attribute — accessed as t.fahrenheit (no parentheses). On the class itself, Temperature.fahrenheit is the property descriptor object. Properties allow computed attributes with validation.class Point: def __init__(self, x, y): self.x, self.y = x, y def __eq__(self, other): return self.x == other.x and self.y == other.y p1 = Point(1, 2) p2 = Point(1, 2) d = {p1: "value"}
__eq__, Python automatically sets __hash__ to None, making the class unhashable. If you want objects to be both equatable and usable as dict keys, you must explicitly define __hash__: def __hash__(self): return hash((self.x, self.y)).class A: pass a1 = A() a2 = A() print(a1 == a2) print(a1 is a2)
__eq__, Python's default equality check for objects is identity — same as is. Two different instances of A are never equal by default, even if they have the same (empty) state. This differs from value types like int/str where equality is by value.from dataclasses import dataclass @dataclass class Point: x: int y: int p1 = Point(1, 2) p2 = Point(1, 2) print(p1) print(p1 == p2)
@dataclass automatically generates __init__, __repr__, and __eq__. Two Points with the same values are equal (__eq__ compares fields). The default repr is human-readable. This saves writing boilerplate for data-holding classes.class A: def method(self): return "A" class B(A): def method(self): return super().method() + "B" class C(B): def method(self): return super().method() + "C" print(C().method())
class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance a = Singleton() b = Singleton() print(a is b)
__new__ controls object creation (called before __init__). This implements the Singleton pattern — only one instance is ever created. After the first call, _instance is set, so subsequent calls return the same object. a is b confirms they are the exact same object.class A: def __init__(self): self.x = 1 a = A() print(a.__dict__)
__dict__ holds only the instance's own attributes (not class attributes, not methods). self.x = 1 adds x to the instance dict. Class-level things (methods, class attributes) live in A.__dict__. This is how Python's attribute lookup works under the hood.