Events: The Python Way

Gianmaria gianmaria at hotmail.com
Sun Jul 29 16:14:52 EDT 2007


"David Wilson" <dw at botanicus.net> ha scritto nel messaggio 
news:mailman.1295.1185665717.22759.python-list at python.org...
> Hi there,
>
> Python has no built-in way of doing this. You may consider writing
> your own class if you like this pattern (I personally do):
>
> class Event(object):
>    def __init__(self):
>        self.subscribers = set()
>
>    def __iadd__(self, subscriber):
>        self.subscribers.add(subscriber)
>        return self
>
>    def __isub__(self, subscriber):
>        self.subscribers.pop(subscriber)
>        return self
>
>    def __call__(self, *args, **kwargs):
>        for subscriber in self.subscribers:
>            subscriber(*args, **kwargs)
>
>
> def HandleFoo(strng):
>    print "HandleFoo:", strng
>
> OnFoo = Event()
> OnFoo += HandleFoo
>
> OnFoo("Test.")
>
>
> On 29/07/07, Gianmaria <gianmaria at hotmail.com> wrote:
>> Hi,
>> i'm a .net programmer and i'm learnig python, so this question can be 
>> very
>> stupid or easy for python programmers. I've a doubt about events.... here 
>> is
>> what:
>>
>> in c# for example i can write a delegate and an event in this way...
>>
>> public delegate SomethingChangedHandler(string message);
>> public event SomethingChangedHandler SomethingChanged;
>>
>> and later in the code fire this event in this way...
>>
>> if(SomethingChanged != null)
>> {
>>     SomethingChanged("Nothing important");
>> }
>>
>> and the subscription of this event of other objects can be easy as
>>
>> eventGeneratorObject.SomethingChanged += new
>> SomethingChangedHandler(aFunctionto_takecareof_it);
>>
>> and even the handlig of the event is aesy...
>>
>> void aFunctionto_takecareof_it(string msg)
>> {
>>
>> }
>>
>>
>> ....now the question is.. how can i do the same using Python? Every help 
>> is
>> appreciated
>>
>>
>>
>>
>>
>> Regards,
>> Gianmaria
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>

Txs so much.
Gianmaria 




More information about the Python-list mailing list