Most developers believe __init__ is the constructor. It is actually the initializer. The true constructor is __new__ .
class NonNegative: 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, 0) def __set__(self, instance, value): if value < 0: raise ValueError(f"self.name cannot be negative.") instance.__dict__[self.name] = value class Product: price = NonNegative() quantity = NonNegative() def __init__(self, name, price, quantity): self.name = name self.price = price self.quantity = quantity Use code with caution.
Methods are functions that receive self implicitly. Bound methods are callable objects. python 3 deep dive part 4 oop
When two subclasses inherit from the same superclass, and a fourth class inherits from both subclasses, a diamond shape forms.
class IntegerField: def __set_name__(self, owner, name): # Python 3.6+ helper to automatically capture the attribute name self.protected_name = f"_name" def __get__(self, instance, owner): if instance is None: return self return getattr(instance, self.protected_name, 0) def __set__(self, instance, value): if not isinstance(value, int): raise TypeError(f"Value must be an integer, got type(value)") setattr(instance, self.protected_name, value) class UserProfile: age = IntegerField() user = UserProfile() user.age = 30 # Works perfectly # user.age = "thirty" # Raises TypeError Use code with caution. 3. Demystifying Multiple Inheritance and the MRO Most developers believe __init__ is the constructor
Properties allow you to expose attributes like public fields while maintaining absolute control over validation behind the scenes.
def area(self): return 3.14 * self.radius ** 2 class NonNegative: def __set_name__(self, owner, name): self
: Stores methods, class variables, and other definitions.
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance Use code with caution. 3. Advanced Attribute Control: Properties and Descriptors