Python - Attribute Access: __getattr__ and __setattr__

Introduction

In Python, classes can intercept basic attribute access.

Demo

class Empty: 
    def __getattr__(self, attrname):           # On self.undefined 
        if attrname == 'age': 
            return 40 
        else: # from   ww  w  . ja  v a 2  s  . co m
            raise AttributeError(attrname) 

X = Empty() 
print( X.age )
print( X.name )

Result

Here, the Empty class and its instance X have no real attributes of their own.

The access to X.age gets routed to the __getattr__ method.

The class makes age look like a real attribute by returning a real value.

Related Topics