[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

different instances with different data descriptors with the same name

Fabrizio Pollastri

2/18/2008 10:21:00 AM

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
2 Answers

Peter Otten

2/18/2008 11:37:00 AM

0

Fabrizio Pollastri 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.

You can invent a naming convention and then invoke the getter/setter
explicitly:

>>> class A(object):
.... def __getattr__(self, name):
.... if not name.startswith("_prop_"):
.... return getattr(self, "_prop_" + name).__get__(self)
.... raise AttributeError(name)
....
>>> a = A()
>>> a.p
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __getattr__
File "<stdin>", line 5, in __getattr__
AttributeError: _prop_p
>>> a._prop_p = property(lambda self: self.x * self.x)
>>> a.x = 42
>>> a.p
1764

But what are you really trying to do?

Peter

Gerard Flanagan

2/18/2008 12:18:00 PM

0

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