Re: different instances with different data descriptors with the same name
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 -- http://mail.python.org/mailman/listinfo/python-list
Re: different instances with different data descriptors with the same name
On Feb 18, 11:21 am, Fabrizio Pollastri [EMAIL PROTECTED] 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: 0 1 5 Traceback (most recent call last): ... AttributeError: 'Obj' object has no attribute 'x' Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: different instances with different data descriptors with the same name
En Mon, 18 Feb 2008 08:21:11 -0200, Fabrizio Pollastri [EMAIL PROTECTED] escribi�: 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. Use __getattr__ or change dynamically each instance's class. See this recent thread: http://groups.google.com/group/comp.lang.python/browse_frm/thread/bfc093464dd6ba9/ -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list