In this lesson, you will learn how to intercept and customize what happens behind the scenes whenever your code reads or writes an object's attributes.
Normally, when you access my_obj.name, Python simply looks up the value in the object's __dict__. However, you can take full control of this process using special "magic" methods.
The Big Three: __getattribute__, __getattr__, and __setattr__
__getattribute__(self, name): This method is the "gatekeeper." It is called every single time you try to access any attribute on an object. Because it is so powerful, you must be careful; if you try to accessself.some_attrinside this method, you will trigger an infinite loop! Always useobject.__getattribute__(self, name)to access values safely.__getattr__(self, name): This acts as a fallback. It is only called if Python cannot find the attribute through normal means. It’s perfect for creating "lazy" attributes or handling missing data gracefully.__setattr__(self, name, value): This is triggered whenever you assign a value to an attribute (e.g.,obj.x = 10). You can use this to add validation logic or log changes.
Practical Example
Imagine we want an object that logs every time we try to access a missing attribute instead of just crashing:
class Logger:
def __getattr__(self, name):
return f"Attribute '{name}' does not exist!"
def __setattr__(self, name, value):
print(f"Setting {name} to {value}")
super().__setattr__(name, value)
obj = Logger()
obj.speed = 100 # Triggers __setattr__
print(obj.power) # Triggers __getattr__ (output: Attribute 'power' does not exist!)
By using __setattr__, we were able to add a print statement to the assignment process. By using __getattr__, we prevented a standard AttributeError and returned a helpful string instead. These tools allow you to create "smart" objects that behave dynamically based on how they are used.
Key Takeaway: Python’s attribute magic methods allow you to hook into the lifecycle of data access, enabling you to add logging, validation, or dynamic behavior to your objects.