W
W
Wynell_ru2020-04-30 18:55:09
Python
Wynell_ru, 2020-04-30 18:55:09

How to catch a dictionary change in Python?

Hello.
Surely this came to your mind immediately:

class State:
    def __init__(self, user_id):
        self.__set_state(user_id)

    def __get_state(self):
        return self.__a

    def __set_state(self, state):
        self.__a = state

    a = property(__get_state, __set_state)

state = State(5)
state.a = 10
state.a # 10

But, alas, I cannot work with dictionaries in the same way: when I try
state = State({'a': "B", 'C': "d"})
state.a['C'] = 8 # TypeError: 'State' object does not support item assignment

produces TypeError: 'State' object does not support item assignment

PS I also need a getter. Not just a setter.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Deleting Account, 2020-04-30
@Wynell_ru

Create a class that will inherit from dict and override the __setitem__ method.
Example:

class NameClass(dict):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.__status_message = kwargs.get("status_message")

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        if self.__status_message:
            print("Я изменил словарь")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question