Otherwise, use composition + dependency injection.
s1 = Singleton() s2 = Singleton() print(s1 is s2) # True python 3 deep dive part 4 oop high quality
class BlueprintValidator(type): def __new__(cls, name, bases, dct): # Validate that all public methods have docstrings for key, value in dct.items(): if not key.startswith('_') and callable(value): if not value.__doc__: raise TypeError(f"Method 'key' in 'name' must have a docstring") return super().__new__(cls, name, bases, dct) class ProductionService(metaclass=BlueprintValidator): def process_data(self): """Fetch and sanitize incoming database payloads.""" return True Use code with caution. Class Decorators vs. Metaclasses Otherwise, use composition + dependency injection
Writing high-quality Python code requires blending these deep mechanics with solid object design principles. Composition Over Inheritance 5. Metaprogramming and Metaclasses
class PositiveNumber: def __set_name__(self, owner, name): self.name = name def __get__(self, instance, owner): if instance is None: return self return instance.__dict__.get(self.name)
: __init__ handles instance setup, but __new__ is the method that actually creates the object. 🎛️ The Descriptor Protocol
: Small, focused classes that provide specific functionality (like logging or JSON serialization) can be "mixed in" to other classes via multiple inheritance without creating deep, rigid hierarchies. 5. Metaprogramming and Metaclasses