Using @property decorator on dicts

后端 未结 2 1325
生来不讨喜
生来不讨喜 2020-12-03 04:04

I\'m trying to use Python\'s @property decorator on a dict in a class. The idea is that I want a certain value (call it \'message\') to be cleared after it is a

2条回答
  •  独厮守ぢ
    2020-12-03 04:27

    class MyDict(dict):
        def __setitem__(self, key, value):
            if key == 'message':
                super().__setitem__('message', '')
                super().__setitem__('last_message', value) 
            else:
                super().__setitem__(key, value)
    
    class A(object):
        def __init__(self):
            self._b = MyDict({"message": "", 
                              "last_message": ""})
    
        @property
        def b(self):
            return self._b
    
    a = A()
    a.b['message'] = 'hello'
    print(a.b['message'])
    # ''
    print(a.b['last_message'])
    # hello
    

    As I think you've discovered, the reason why your setter wasn't working is because

    a.b['message']='hello'
    

    first accesses a.b, which calls the b property's getter, not its setter. The getter returns the dict self._b. Then self._b['message']='hello' causes the dict's __setitem__ is called .

    So to fix the problem, you need a special dict (like MyDict).

提交回复
热议问题