Python - Attribute Assignment and Deletion

Introduction

The __setattr__ intercepts all attribute assignments.

If this method is defined or inherited, self.attr = value becomes self.__setattr__('attr', value).

This allows your class to catch attribute changes, and validate or transform as desired.

Demo

class Accesscontrol: 
   def __setattr__(self, attr, value): 
       if attr == 'age': 
           self.__dict__[attr] = value + 10      # Not self.name=val or setattr 
       else: 
           raise AttributeError(attr + ' not allowed') 

X = Accesscontrol() # from   w ww . j  a v a  2 s .c  o  m
X.age = 40                                        # Calls __setattr__ 
print( X.age )
X.name = 'Bob' 
print(X.name)

Result

Related Topic