如何检测Python类中列表的变化,或者为什么 "setter "不触发?

问题描述 投票:0回答:1

我想在一个Python类中有一个列表,每当列表中的元素发生变化时,我需要运行一些逻辑。每当列表中的一个元素发生变化时,我需要运行一些逻辑。我对python中的类很陌生,我使用setter的方法可能很幼稚。这对我来说是直观的。

class test():
    def __init__(self):
        self._R = [False]*16

    @property
    def R(self):
        return self._R

    @R.setter
    def R(self,a):
        print('Why do I not get reached?')
        self._R = a

W = test()
W.R[0] = True

但是setter从来没有被触发过 如果你能给我一个正确的方向,我将是非常大的充分。

python class getter-setter
1个回答
0
投票

你可以创建一个新的类似List的类,它接收一个回调函数,并在list改变时执行它。

class CallbackList:  # PEP-8 style suggests UpperCase class names
    def __init__(self, callback=None):
        self._list = [False]
        self._callback = callback  # Python functions are first-class objects just like ints, strings, etc, so this is completely legal

    def __setitem__(self, index, value):
        self._list[index] = value
        if self._callback:
            self._callback()  # Executes the callback function whenever a value is set

    def __getitem__(self, index):
        return self._list[index]


class Test:
    def __init__(self):
        self.callback_list = CallbackList(callback=self.foo)

    def foo(self):
        print("You changed the list!")


W = Test()
W.callback_list[0] = True  # This prints "You changed the list!"

请注意,这仍然不能捕捉到所有可能的变化。比如说

W = Test()
some_list = [1, 2, 3]

W.callback_list[0] = some_list  # This triggers the callback function
print(W.callback_list[0])  # [1, 2, 3]

some_list.append(4)  # This does NOT trigger the callback function!
print(W.callback_list[0])  # [1, 2, 3, 4] !

0
投票

我试着按照@user2357112supportsMonica的评论写代码:

class test():
    def __init__(self):
        self.A = 1

    def foo(self):
        print(self.A)

    class R_Class():
        def __init__(self):
            self._R = [False]*16

        def __setitem__(self,index,value):
            self._R[index] = value
            test.foo() #Here I need to call foo somehow
        def __getitem__(self,index):
            return self._R[index]
    R = R_Class()


W = test()
W.R[0] = True


但这种方法又导致了另一个问题,有没有办法在子类中正确调用foo函数?

© www.soinside.com 2019 - 2024. All rights reserved.