__getattr__Easy Examples

Called when the default attribute access fails

Implementing __getattr__

Basic implementation of __getattr__ in a class.

python
class Example:
    def __getattr__(self):
        return "Example __getattr__"

obj = Example()
print(obj)

__getattr__ called when the default attribute access fails. Implementing it lets you customize how Python interacts with your objects.

__getattr__ in action

Seeing __getattr__ called by Python's built-in operations.

python
# How Python calls __getattr__ automatically
class Demo:
    def __init__(self, value):
        self.value = value

    def __getattr__(self):
        print(f"__getattr__ was called!")
        return self

d = Demo(42)
# This triggers __getattr__:
print(d)

Python automatically calls __getattr__ when you use the corresponding operator or function on your object.

Want to try these examples interactively?

Open Easy Playground