如何在值更改时触发函数?

2024-05-16 01:42:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我意识到这个问题与事件处理有关,我已经阅读了Python事件处理程序a dispatchers,所以要么它没有回答我的问题,要么我完全错过了信息。

我希望每当值v发生更改时触发对象A的方法m()

例如(假设金钱使人快乐):

global_wealth = 0

class Person()
    def __init__(self):
        self.wealth = 0
        global global_wealth
        # here is where attribute should be
        # bound to changes in 'global_wealth'
        self.happiness = bind_to(global_wealth, how_happy)

    def how_happy(self, global_wealth):
        return self.wealth / global_wealth

因此,每当global_wealth值发生更改时,类Person的所有实例都应该相应地更改其happiness值。

注意:我不得不编辑这个问题,因为第一个版本似乎暗示我需要getter和setter方法。对不起,我有点困惑。


Tags: to方法self信息处理程序def事件global
3条回答

如果要在属性更改时执行代码,可以使用属性。请注意,在更改属性时发生的巨大副作用或显著开销对于使用API的任何人来说都有点奇怪,因此在某些情况下,您可能希望通过使用方法来避免这种情况。

class A(object):

    def m(self, p_value):
         print p_value

    @property
    def p(self):
        return self._p 

    @p.setter
    def p(self, value)
        self._p = value
        self.m(value)

你要找的是所谓的(Functional) Reactive Programming对于普通的Lisp,有单元格–请参见Cells projectCells manifesto;对于python,有Trellis library

电子表格也使用同样的范例。对于跟踪多个相关参数非常有用,例如在GUI编程中。

反应式编程类似于观察者模式,但有一个重要的区别:

Similarities with Observer pattern However, integrating the data flow concepts into the programming language would make it easier to express them, and could therefore increase the granularity of the data flow graph. For example, the observer pattern commonly describes data-flows between whole objects/classes, whereas object-oriented reactive programming could target the members of objects/classes.

你需要使用Observer Pattern。 在下面的代码中,一个人订阅接收来自全球财富实体的更新。当全球财富发生变化时,该实体会提醒所有订户(观察员)发生变化。然后这个人会自我更新。

我在本例中使用了属性,但它们不是必需的。一个小小的警告:属性只对新样式的类起作用,因此类声明之后的(对象)是必需的。

class GlobalWealth(object):
    def __init__(self):
        self._global_wealth = 10.0
        self._observers = []

    @property
    def global_wealth(self):
        return self._global_wealth

    @global_wealth.setter
    def global_wealth(self, value):
        self._global_wealth = value
        for callback in self._observers:
            print('announcing change')
            callback(self._global_wealth)

    def bind_to(self, callback):
        print('bound')
        self._observers.append(callback)


class Person(object):
    def __init__(self, data):
        self.wealth = 1.0
        self.data = data
        self.data.bind_to(self.update_how_happy)
        self.happiness = self.wealth / self.data.global_wealth

    def update_how_happy(self, global_wealth):
        self.happiness = self.wealth / global_wealth


if __name__ == '__main__':
    data = GlobalWealth()
    p = Person(data)
    print(p.happiness)
    data.global_wealth = 1.0
    print(p.happiness)

相关问题 更多 >