class — Advanced Examples
Defines a new class (blueprint for creating objects)
Multiple inheritance and MRO
Using multiple inheritance with method resolution order.
python
class Loggable: def log(self, message): print(f"[{self.__class__.__name__}] {message}") class Serializable: def to_dict(self): return {k: v for k, v in self.__dict__.items() if not k.startswith("_")} class User(Loggable, Serializable): def __init__(self, name, email): self.name = name self.email = email u = User("Alice", "alice@example.com") u.log("created") print(u.to_dict()) # Method Resolution Order print(User.__mro__)
Python uses C3 linearization for MRO. Multiple inheritance lets you compose behaviors from several base classes, but order matters.
Slots and memory optimization
Using __slots__ to restrict and optimize attribute storage.
python
import sys class PointDict: def __init__(self, x, y): self.x = x self.y = y class PointSlots: __slots__ = ("x", "y") def __init__(self, x, y): self.x = x self.y = y pd = PointDict(1, 2) ps = PointSlots(1, 2) print(f"With __dict__: {sys.getsizeof(pd.__dict__)} bytes") print(f"With __slots__: no __dict__") print(f"ps.x = {ps.x}, ps.y = {ps.y}") try: ps.z = 3 except AttributeError as e: print(f"Cannot add attribute: {e}")
__slots__ prevents __dict__ creation, saving ~40-60 bytes per instance. Useful when creating millions of objects.
Want to try these examples interactively?
Open Advanced Playground