class Bad: def __init__(self, items=[]): self.items = items # Shared across all instances!
def greet(self): return f"Hello, self.name!"
decorator, as well as read-only, computed, and deletable properties. Polymorphism and Special Methods : The role of "Dunder" (double underscore) methods like , arithmetic operators, and rich comparisons. Single Inheritance python 3 deep dive part 4 oop
In this example, the BankAccount class encapsulates the balance attribute and provides methods to access and modify it.
In Python, a class definition creates a class object. When you call the class, you create an instance object. Both possess their own namespaces, stored in a dictionary attribute named __dict__ . class Bad: def __init__(self, items=[]): self
In Python, everything is an object . An integer, a string, a function, even a class itself—they are all instances of some class. This is the core of Python’s OOP.
In this example, the BankAccount class has a private variable __balance that can only be accessed through the get_balance method. Single Inheritance In this example, the BankAccount class
When you access an attribute like obj.x , Python follows a specific lookup chain:
# type(name, bases, dict) CustomClass = type('CustomClass', (object,), 'version': 1.0, 'greet': lambda self: "Hello") instance = CustomClass() print(instance.greet()) # Output: Hello Use code with caution. Writing Custom Metaclasses
class Circle: def __init__(self, radius): self._radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, value): if value > 0: self._radius = value else: raise ValueError("Radius must be positive") Use code with caution. 5. Inheritance and Polymorphism
You can intercept class creation by writing a custom metaclass. This allows you to enforce architectural rules, auto-register plugins, or modify class attributes at creation time.