0

I have an object of objects and want to know when a sub-object has changed. I understand how to use __setattr__ for primitive types but do not understand how to use it with objects. I guess python uses points and that is way __setattr__ is not called on the outer object once an element in the inner object is changed.

class OuterChangeDetection(object):
    def __setattr__(self, key, value):
        super().__setattr__(key, value)
        print('OuterChangeDetection', key, value)


class InnerChangeDetection(object):
    def __setattr__(self, key, value):
        super().__setattr__(key, value)
        print('InnerChangeDetection', key, value)


class Fruit(InnerChangeDetection):
    def __init__(self, weight: int):
        self.weight = weight


class Vegetable(InnerChangeDetection):
    def __init__(self, weight: int):
        self.weight = weight


class Basket(OuterChangeDetection):
    apple: Fruit = Fruit(1)
    banana: Fruit = Fruit(2)
    potato: Vegetable = Vegetable(3)

    def remove_bananas(self):
        self.banana = None


if __name__ == '__main__':
    basket = Basket()
    basket.apple.weight *= 10
    basket.banana.weight *= 10
    basket.potato.weight *= 10

    basket.remove_bananas()

Output:

InnerChangeDetection weight 1
InnerChangeDetection weight 2
InnerChangeDetection weight 3
InnerChangeDetection weight 10
InnerChangeDetection weight 20
InnerChangeDetection weight 30
OuterChangeDetection banana None

I would also like to trigger OuterChangeDetection when I change the weight so I know which element in the Basket has been changed.

HennyKo
  • 712
  • 1
  • 8
  • 19

0 Answers0