python on event triggers

Solutions on MaxInterview for python on event triggers by the best coders in the world

showing results for - "python on event triggers"
Ange
02 Jun 2017
1"""
2You need to use the Observer Pattern (http://en.wikipedia.org/wiki/Observer_pattern). 
3In the following code, a person subscribes to receive updates from the global wealth entity. 
4When there is a change to global wealth, this entity then alerts all 
5its subscribers (observers) that a change happened. Person then updates itself.
6
7I make use of properties in this example, but they are not necessary. 
8A small warning: properties work only on new style classes, so 
9the (object) after the class declarations are mandatory for this to work.
10"""
11
12
13class GlobalWealth(object):
14    def __init__(self):
15        self._global_wealth = 10.0
16        self._observers = []
17
18    @property
19    def global_wealth(self):
20        return self._global_wealth
21
22    @global_wealth.setter
23    def global_wealth(self, value):
24        self._global_wealth = value
25        for callback in self._observers:
26            print('announcing change')
27            callback(self._global_wealth)
28
29    def bind_to(self, callback):
30        print('bound')
31        self._observers.append(callback)
32
33
34class Person(object):
35    def __init__(self, data):
36        self.wealth = 1.0
37        self.data = data
38        self.data.bind_to(self.update_how_happy)
39        self.happiness = self.wealth / self.data.global_wealth
40
41    def update_how_happy(self, global_wealth):
42        self.happiness = self.wealth / global_wealth
43
44
45if __name__ == '__main__':
46    data = GlobalWealth()
47    p = Person(data)
48    print(p.happiness)
49    data.global_wealth = 1.0
50    print(p.happiness)