Externally-defined properties?

Terry Hancock hancock at anansispaceworks.com
Wed Aug 24 02:15:03 EDT 2005


Frankly, I was surprised this worked at all, but I tried
creating a property outside of a class (i.e. at the module
level), and it seems to behave as a property:

>>> def get_x(ob):
...     global x
...     return str(x)
...
>>> def set_x(ob, value):
...     global x
...     x = int(value)
...
>>> def del_x(ob):
...     global x
...     del x
...
>>> def x_access():
...     return property(get_x, set_x, del_x, "X defined externally?")
...
>>>
>>> class Accessor(object):
...     s_x = x_access()
...     def __str__(self):
...         print "Accessor has x = %s" % self.s_X
...
>>> a = Accessor()
>>> a.s_x = 3
>>> a.s_x
'3'
>>> dir()
['Accessor', '__builtins__', '__doc__', '__name__', 'a', 'del_x', 'get_x', 'p', 'set_x', 'x', 'x_access']
>>> x
3

(of course in the real example, x will probably be in an
entirely different module, used as a library -- the client code
just calls a function to get a property that is automatically
managed for it).

So far, the only problem I see is that it only works if the
property is assigned to a new-type class attribute (otherwise,
the first assignment simply replaces the property).

I'm thinking of using this to tie a property of a class to an
external data source (a joystick axis, in fact -- or at least
its last-polled value).

There is a more convential way to do this, of course -- I could
just use a "get_value" function, but there is something attractive
about have a variable that is simply bound to the external
data source like this.  It seems like a good way to encapsulate
functionality that I don't really want the high level class to
have to "think" about.

I mention it here, because I've never seen a property used
this way.  So I'm either being very clever, or very dumb, 
and I would be interested in opinions on which applies. ;-)

Am I about to shoot myself in the foot?

Cheers,
Terry
 
--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list