Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Python .on event triggers

"""
You need to use the Observer Pattern (http://en.wikipedia.org/wiki/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 = []

    @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)
Comment

PREVIOUS NEXT
Code Example
Python :: django error displaying images page not found 
Python :: join on index python 
Python :: get sum of column before a date python 
Python :: __floordiv__ 
Python :: crawling emails with python 
Python :: python boucle for 
Python :: python time.sleep 
Python :: python socket github 
Python :: spacy import doc 
Python :: find daily aggregation in pandas 
Python :: pandas data frame from part of excel better example 
Python :: np append 
Python :: Python Deleting a Tuple 
Python :: map in python 
Python :: graphics.py how to make a button 
Python :: sort np list of string 
Python :: python dataframe add row 
Python :: how to use with statement in python 2.5 and earlier 
Python :: Flask / Python. Get mimetype from uploaded file 
Python :: how to get checkbutton from a list 
Python :: how to add find the smallest int n in a list python 
Python :: django table view sort filter 
Python :: how to access a txt file through os library in python 
Python :: 151 - Power Crisis solution 
Python :: python sum only numbers 
Python :: pandas flip x and y axis 
Python :: How to convert datetime in python 
Python :: check if binary tree is balanced python 
Python :: how to swirtch the placement of the levels in pandas 
Python :: bitwise operators in python 
ADD CONTENT
Topic
Content
Source link
Name
7+8 =