Get and set class properties
Overload __getattr__ and __setattr__
We can add properties to old-style classes. with magic methods rather than the property function.
The following four methods provide all the functionality you need in old-style classes.
- __getattribute__(self, name) is called when the attribute name is accessed. Works correctly on new-style classes only.
- __getattr__(self, name) is called when the attribute name is accessed and the object has no such attribute.
- __setattr__(self, name, value) is called when an attempt is made to bind the attribute name to value.
- __delattr__(self, name) is called when an attempt is made to delete the attribute name.
class Rectangle:
def __init__(self):
self.width = 0 # from ww w.ja va 2 s .com
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