如何触发价值变动的功能? [英] How to trigger function on value change?

查看:92
本文介绍了如何触发价值变动的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I realise this question has to do with event-handling and i've read about Python event-handler a dispatchers, so either it did not answer my question or i completely missed out the information.

我想要方法 m()对象 A 每当值 v 正在变化:

I want method m() of object A to be triggered whenever value v is changing:

例如(假设钱开心):

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 的所有实例应更改其 happines

So whenever the global_wealth value is changed, all instances of the class Person should change their happiness value accordingly.

注意:我不得不编辑这个问题,因为第一个版本似乎建议我需要吸气剂和固定剂的方法。对不起,感到困惑。

NB: I had to edit the question since the first version seemed to suggest i needed getter and setter methods. Sorry for the confusion.

推荐答案

你需要使用,rel =noreferrerwikipedia.org/wiki/Observer_pattern。
在下面的代码中,一个人订阅从全球财富实体接收更新。当全球财富发生变化时,该实体会向所有订阅者(观察员)发出更改。然后人们进行更新。

You need to use the Observer Pattern. In the following code, a person subscribes to receive updates from the global wealth entity. When there is a change to global wealth, this entity then alerts all its subscribers (observers) that a change happened. Person then updates itself.

在本示例中,我利用属性,但不是必需的。一个小小的警告:属性只适用于新的样式类,所以(对象)在类声明之后是强制性的。

I make use of properties in this example, but they are not necessary. A small warning: properties work only on new style classes, so the (object) after the class declarations are mandatory for this to work.

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

    def get_wealth(self):
        return self._global_wealth

    def set_wealth(self, value):
        self._global_wealth = value
        for callback in self._observers:
            print 'anouncing change'
            callback(self._global_wealth)

    global_wealth = property(get_wealth, set_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

这篇关于如何触发价值变动的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆