問題描述
我意識到這個問題與事件處理有關,并且我已經閱讀了有關 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.
我希望在值 v
發生變化時觸發對象 A
的方法 m()
:
I want method m()
of object A
to be triggered whenever value v
is changing:
例如(假設金錢使人快樂):
For instance (assuming money makes happy):
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
值.
So whenever the global_wealth
value is changed, all instances of the class Person
should change their happiness
value accordingly.
NB:我不得不編輯這個問題,因為第一個版本似乎表明我需要 getter 和 setter 方法.很抱歉造成混亂.
NB: I had to edit the question since the first version seemed to suggest i needed getter and setter methods. Sorry for the confusion.
推薦答案
你需要使用 觀察者模式.在以下代碼中,一個人訂閱接收來自全球財富實體的更新.當全球財富發生變化時,該實體會提醒其所有訂閱者(觀察者)發生變化.Person 然后更新自己.
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.
我在這個例子中使用了屬性,但它們不是必需的.一個小警告:屬性僅適用于新樣式類,因此類聲明后的 (object) 是強制性的.
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 = []
@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)
這篇關于如何觸發價值變化的功能?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!