Observer implementation question ('Patterns in Python')

Anders Dahnielson anders.dahnielson at gmail.com
Sat Oct 13 00:07:48 CEST 2007


Sorry if this is a somewhat silly question...

I'm using the Observer implementation found in 'Patterns in
Python' [1] and find it really neat. But, I have not yet fully groked
the new-style class, classic class and property differences involved.
So can somebody please explain to me why this works (using a classic
class):

        class C:
            TheEvent = Event()
            def OnTheEvent(self):
                self.TheEvent(self, context)

        instance = C()
        instance.TheEvent += callback
        instance.OnTheEvent()
        instance.TheEvent -= callback

While this do not (using new-style class):

        class C(object):
            TheEvent = Event()
            def OnTheEvent(self):
                self.TheEvent(self, context)

        instance = C()
        instance.TheEvent += callback
        instance.OnTheEvent()
        instance.TheEvent -= callback

Raising an AttributeError :

        Traceback (most recent call last):
          File "sig_test.py", line 7, in ?
             instance.TheEvent += callback
        AttributeError: can't set attribute

So far I've figured out that it is the Event class (subclassing the
built-in property type) that is the culprit, but not why. (See
'Patterns in Python' [1] for code listing of the Event class.)

I would be grateful if some helpful soul could explain it.

[1] http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#observer




More information about the Python-list mailing list