Properties, Methods, Events
transpicio at yahoo.com.au
Tue May 8 17:28:02 CEST 2001
"Alex Martelli" <aleaxit at yahoo.com> wrote in message
news:9d8ltl01frp at news2.newsguy.com...
[ excellent example of "properties" in Python ]
> [...] -- the getters and setters
> will now automatically be called when appropriate, upon
> client-code use of attribute-syntax.
It solves the 'properties' half of the problem very nicely.
The other part I'm interested in is the event-handling part. Having all the
event-handling code in the getters and setters means that the object is
responding to its own changes (which is fine, much of the time). But it
would also be nice to have a way of hooking up other message handlers at
runtime, in a way that the designer of the object emitting the messages need
Eg. Time bomb emits 'tick' and 'explode' events. It doesn't care who
responds, or how. Neighbouring objects - instances of Policeman,
ExplosivesExpert, Barber, etc, definitely want to respond in different ways
to the tick notifications (though I guess the reaction to 'explode' is
pretty generic) ;-)
Following on from your example, it's trivial to make an Events mixin that
maybe contains a dictionary mapping event-names to a list of event-handlers.
If an event-handler is present, it can be automatically invoked by the
__setattr__ method. But, this only applies to _get_ and _set_ events.
Do you know of any way to trap an ordinary method call? Eg. if TimeBomb has
a method 'tick', can we find a way to know automatically when it is called?
I know it would be easy to work around this on a case by case basis, but if
there's a way of wrapping this up in another mixin, it could be _really_
elegant. Unfortunately, I don't have much of a clue at this stage. This
metaclass stuff is all pretty new to me.
> [...] You can freely expose your
> attributes to client code, AND switch to getter and setter
> methods, *transparently to client code*, if and when you
> find out a given attribute needs to be 'wrapped' upon
> access and/or setting. "Do the simplest thing that could
> possibly work", &c. I believe this possibility is in fact
> what makes Python-inappropriate the common Java/C++ idiom
> of exposing any attribute you DO need to expose through
> getter and setter methods *ALWAYS*, "just in case".
Totally agree. I think public-by-default, combined with the
properties/events combo for trickier circumstances is much friendlier to
clients than exposing only the getters and setters. Which makes me think it
> [...] deserves a Cookbook recipe...
More information about the Python-list