Properties, Methods, Events

John Flynn transpicio at yahoo.com.au
Tue May 8 05:30:25 CEST 2001


I quite like the simple Properties-Methods-Events paradigm used by Delphi
(and recently C#).

For those who aren't familiar with it, it's something like this:

Suppose you have a class with private data. You want to provide read-only,
write-only or read-write access to the private data. In C++ or Java you
might provide getX() and/or setX() methods. Properties are an alternative to
getX, setX.

>From outside the class, properties are used exactly like public fields, but
inside the class they may be implemented as methods or functions that do
other things besides getting or setting X. (Eg. a GUI widget might want to
repaint itself whenever one of its visible attributes changes).

So far it's just syntax sugar. Eg:
Instead of:   colour.setRed(colour.getRed() + 1)
You might say:   colour.red += 1

Properties aren't much good on their own, but they're often used in
combination with Events. For example, you might want to notify other
(unknown) objects of runtime changes to one of your object's properties, but
at design time you have no idea which other objects will need to be
notified.

So you provide an Event that can have any number of event handlers attached
to it at runtime. When the event occurs (eg. attribute's value is changed),
the event handlers are invoked and whoever needs to be notified of the event
is automatically notified. (If I understand it correctly, this is what Qt
does with its signals / slots mechanism).

(Of course, properties aren't necessary for this kind of event handling, but
I quite like them anyway).

My question is: has anyone emulated this in Python, eg. by overriding
__setattr__ ?

I'm going to try this out for fun, but I'd be interested to hear of anyone's
views on how it is best done in Python (or why it shouldn't be done at all)
;-)







More information about the Python-list mailing list