Python 3 Deep Dive Part 4 Oop -

@abstractmethod def perimeter(self): pass class Circle(Shape): def (self, radius): self.radius = radius

class A: pass class B(A): pass class C(A): pass class D(B, C): pass print(D.) (D, B, C, A, object)

If you think OOP in Python is just about writing class and self , think again. In this fourth part, we will go beyond the basics and deep dive into Python’s object model, method resolution order (MRO), descriptors, abstract base classes, and metaprogramming. python 3 deep dive part 4 oop

Creating 10 million instances: FastPoint uses ~50% less memory and is ~15% faster to access. 8.1 Mutating Default Arguments in Methods class Bad: def __init__(self, items=[]): self.items = items # Shared across all instances! class Good: def init (self, items=None): self.items = items or [] 8.2 Overusing Inheritance for Code Reuse Prefer composition over inheritance unless there is a genuine "is-a" relationship. 8.3 Forgetting to Call super().__init__() In multiple inheritance, failing to call super().__init__() can break the MRO chain and leave attributes uninitialized. 9. Real-World Example: A Plugin System Combine several OOP concepts: ABCs, metaclass auto-registration, and descriptors.

db1 = Database() db2 = Database() print(db1 is db2) # True (singleton) class RequiredAttrsMeta(type): def __new__(cls, name, bases, dct): if 'name' not in dct: raise TypeError(f"Class {name} missing 'name' attribute") return super().__new__(cls, name, bases, dct) class Person(metaclass=RequiredAttrsMeta): name = "John" # If omitted, TypeError at class definition time 6. Advanced OOP Patterns in Python 6.1 The Composition Over Inheritance Principle Instead of deep inheritance trees, use composition: TypeError at class definition time 6.

def drive(self): self.engine.start() for w in self.wheels: w.rotate() A mixin is a small class that provides specific behavior but is not meant to stand alone.

class PrintPlugin(Plugin): def run(self): print("Print plugin running") C): pass print(D.) (D

class Engine: def start(self): pass class Wheels: def rotate(self): pass