Dynamic properties
Nick Coghlan
ncoghlan at iinet.net.au
Fri Jan 21 10:21:14 EST 2005
michael wrote:
> My first try is :
>
> fget = lambda self: mygetattr(self, attrname)
> fset = lambda self, value: mysetattr (self, attrname, value)
> fdel = lambda self: mydelattr(self, attrname)
>
> # fget, fset, fdel are used to reconstruct the byte field
>
> setattr (self, key, property (fget, fset, fdel))
setattr creates entries in the instance dictionary of the object that is passed
in. Properties need to be stored in the object type's dictionary in order to
work their magic. I also believe it is required that the class be a new-style class.
So try something like (Python 2.4):
Py> def mygetattr(self, attr):
... print "Getting %s from %s" % (str(attr), str(self))
...
Py> def mysetattr(self, attr, value):
... print "Setting %s to %s on %s" % (str(attr), str(value), str(self))
...
Py> def mydelattr(self, attr):
... print "Deleting %s from %s" % (str(attr), str(self))
...
Py> class C(object):
... @classmethod
... def make_properties(cls, attrs):
... for attr in attrs:
... # Use default arguments to bind attr *now*, not at call time
... def _get(self, attr=attr):
... return mygetattr(self, attr)
... def _set(self, value, attr=attr):
... mysetattr(self, attr, value)
... def _del(self, attr=attr):
... mydelattr(self, attr)
... setattr(cls, attr, property(_get, _set, _del))
...
Py> properties = ["x", "y"]
Py> C.make_properties(properties)
Py> C.x
<property object at 0x00A9D3F0>
Py> c = C()
Py> c.x
Getting x from <__main__.C object at 0x00A9A990>
Py> c.x = 1
Setting x to 1 on <__main__.C object at 0x00A9A990>
Py> del c.x
Deleting x from <__main__.C object at 0x00A9A990>
Py> c.y
Getting y from <__main__.C object at 0x00A9A990>
Py> c.y = 1
Setting y to 1 on <__main__.C object at 0x00A9A990>
Py> del c.y
Deleting y from <__main__.C object at 0x00A9A990>
The decorator syntax is the only 2.4'ism I'm aware of in that code, so porting
to 2.3 or even 2.2 shouldn't be an issue.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at email.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
More information about the Python-list
mailing list