different instances with different data descriptors with the same name

F

Fabrizio Pollastri

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
 
P

Peter Otten

Fabrizio said:
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:
.... def __getattr__(self, name):
.... if not name.startswith("_prop_"):
.... return getattr(self, "_prop_" + name).__get__(self)
.... raise AttributeError(name)
....Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __getattr__
1764

But what are you really trying to do?

Peter
 
G

grflanagan

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

Outputs:

00000
00001
00005
Traceback (most recent call last):
...
AttributeError: 'Obj' object has no attribute 'x'


Gerard
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,125
Latest member
VinayKumar Nevatia_
Top