Gerard Flanagan
2/18/2008 12:18:00 PM
On Feb 18, 11:21 am, Fabrizio Pollastri <f.pollas...@inrim.it> wrote:
> Data descriptors are set as attributes of object types. So if one has many
> instances of the same class and wants each instance to have a different property
> (data descriptor) that can be accessed with a unique attribute name, it seems to
> me that there is no solution with data descriptors. There is any workaround to
> this? Thank in advance for any help.
>
> F. Pollastri
If you explain your intent you might get some good advice. Here's one
idea:
[code]
class Descriptor(object):
val = 0
def __init__(self, initval=0):
self.val = initval
def __get__(self, obj, objtype):
return '%05d' % self.val
def __set__(self, obj, val):
self.val = val
def Factory(attrname, initval=0):
class Obj(object):
pass
setattr(Obj, attrname, Descriptor(initval))
return Obj
X = Factory('x')
Y = Factory('y', 1)
obj1 = X()
print obj1.x
obj2 = Y()
print obj2.y
obj2.y = 5
print obj2.y
print obj2.x
[/code]
Outputs:
00000
00001
00005
Traceback (most recent call last):
...
AttributeError: 'Obj' object has no attribute 'x'
Gerard