Python - Attribute Access: __getattr__ and __setattr__


In Python, classes can intercept basic attribute access.


class Empty: 
    def __getattr__(self, attrname):           # On self.undefined 
        if attrname == 'age': 
            return 40 
        else: # from w  w  w. j av  a2  s.c  o  m
            raise AttributeError(attrname) 

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


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