Skip to content Skip to sidebar Skip to footer

Python: How To: Attribute Of An Instance Which Depends On Flag, Which Is Itself An Attribute Of That Instance / Object

Consider the following minimal example for my question: class MyClass: a = False b = 0 if a: b = 1 MCinst = MyClass() Here MCinst has two attributes, MCinst.a

Solution 1:

class MyClass:
    a = False
    b = 0     

    def __setattr__(self, key, value):
        if key == 'a':
            setattr(self, 'b', 1)
        super().__setattr__(key, value)

If you actually want to change the class attribute, you can use

setattr(self.__class__, 'b', 1)

Post a Comment for "Python: How To: Attribute Of An Instance Which Depends On Flag, Which Is Itself An Attribute Of That Instance / Object"