I want to use a Python class that recomputes certain attributes whenever other attributes are changed.
In an older question (for Python 2) Martijn Pieters♦ suggested using setattr hook , whenever one wants to use a setter without using the getter instead of for example the property decorator.
In my case, this does not work, as I need all variables to be initialized before I can call the special method setattr(). However, the init method will already call the setattr method before all attributes are initialized as you can see in a simplified example below:
class Cuboid():
def __init__(self, L, W, H):
self.L = L
self.W = W
self.H = H
# Possibly some more attributes...
self.V = self.L*self.W*self.H
def __setattr__(self, key, value):
super().__setattr__(key, value)
if key in ['L', 'W', 'H']:
# Do something if other attributes depende on the variable that is
# set e.g.:
self.V = self.L*self.W*self.H
In the first line of the init method, the setattr() method will be called and it will throw an AttributeError because self.H and self.W are not yet defined.
How do I escape my setattr method during initialization of the instance? Or what's another clean, pythonic way to solve this problem?