__setattr__ — Easy Examples
Called on every attribute assignment
Implementing __setattr__
Basic implementation of __setattr__ in a class.
python
class Example: def __setattr__(self): return "Example __setattr__" obj = Example() print(obj)
__setattr__ called on every attribute assignment. Implementing it lets you customize how Python interacts with your objects.
__setattr__ in action
Seeing __setattr__ called by Python's built-in operations.
python
# How Python calls __setattr__ automatically class Demo: def __init__(self, value): self.value = value def __setattr__(self): print(f"__setattr__ was called!") return self d = Demo(42) # This triggers __setattr__: print(d)
Python automatically calls __setattr__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground