Mega Code Archive

 
Categories / Python Tutorial / Class
 

Setattr and getattr

# __getattribute__(self, name): Automatically called when the attribute name is accessed.  # __getattr__(self, name): Automatically called when the attribute name is accessed and the object has no such attribute. # __setattr__(self, name, value): Automatically called when an attempt is made to bind the attribute name to value. # __delattr__(self, name): Automatically called when an attempt is made to delete the attribute name. class Rectangle:     def __init__(self):         self.width = 0         self.height = 0     def __setattr__(self, name, value):         if name == 'size':             self.width, self.height = value         else:             self.__dict__[name] = value     def __getattr__(self, name):         if name == 'size':             return self.width, self.height         else:             raise AttributeError