2

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?

  • Martijn's answer already shows how to bypass `__setattr__`. After all, the `__setattr__` override needs to bypass itself. Look at how that works. – user2357112 Aug 19 '19 at 16:22
  • Thanks, @user2357112. So your suggestion would be to replace self.L = L with super().__setattr__('L', L) in the __init__() method? Would this be considered good practice? – FrankHauser Aug 19 '19 at 16:34

0 Answers0