当类变量发生变化时如何调用特定函数?

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

我创建了一个类并初始化了三个变量a、b和c。现在我想在变量 a 或 c 从外部更改时调用特定函数

func1
,并在变量 b 从外部更改时调用函数
func2

我知道这可以使用装饰器来完成,如下所示:

class Event:
    def __init__(self, a, b, c):
        self._a = a
        self._b = b
        self._c = c

    @property
    def a(self):
        return self._a
    @a.setter
    def a(self, value):
        self._a = value
        print("Variable a changed!")
        self.func1()

    @property
    def b(self):
        return self._b
    @b.setter
    def b(self, value):
        self._b = value
        print("Variable b changed!")
        self.func2()

    @property
    def c(self):
        return self._c
    @c.setter
    def c(self, value):
        self._c = value
        print("Variable c changed!")
        self.func1()

    def func1(self):
        print("Function 1 called")
    def func2(self):
        print("Function 2 called")

obj = Event(1, 2, 3)
obj.a = 15
obj.b = 10
obj.c = 5

我的最终代码将有 8 个或更多变量,为其中每一个编写一个指定的 @property 和 @var.setter 将非常麻烦并且不具有真正的可读性。

有没有更简单的方法直接说

If variables a, c, f, ... are updated, call function X, if b, e, ... are updated, call function Y

谢谢!

python class attributes decorator
1个回答
0
投票

您可以使用自定义功能对

property
进行子类化。这里有一个关于如何做到这一点的basic示例。请注意,您应该提供一个字典来映射哪个属性触发哪个函数(作为字符串)。

class SetTriggerProperty(property):

    MAPPER = {'a': 'func1', 'b': 'func2', 'c': 'func1'}
    
    def __set__(self, obj, value):
        super().__set__(obj, value)
        func_name = self.MAPPER.get(self.fget.__name__)
        getattr(obj, func_name)()


class Event:
    ...
    @SetTriggerProperty
    def a(self):
        return self._a

    @a.setter
    def a(self, value):
        self._a = value
        print("Variable a changed!")
    ...
© www.soinside.com 2019 - 2024. All rights reserved.