Detect target name in descriptor __set__ method
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Thu Jul 23 19:14:07 EDT 2009
En Thu, 23 Jul 2009 10:19:33 -0300, DG <dangets at gmail.com> escribió:
> On Jul 22, 6:05 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
> wrote:
>> En Wed, 22 Jul 2009 11:01:09 -0300, Rhodri James
>> <rho... at wildebst.demon.co.uk> escribió:
>>
>> > On Wed, 22 Jul 2009 06:02:55 +0100, Gabriel Genellina
>> > <gagsl-... at yahoo.com.ar> wrote:
>>
>> >> class X(object):
>> >> foo = descriptor()
>>
>> >> x = X()
>> >> x.foo = "value"
>>
> You might've already thought of this (and it is annoying), but you
> could pass the name through the descriptor's init method. I believe
> this is the only way besides assigning a metaclass that will look for
> that type of descriptor upon class creation and set the descriptor's
> name at that time.
>
> class A(object):
> def __init__(self, attr_name):
> self._name = attr_name
> def __set__(self, instance, value):
> self.instance.__dict__[self._name] = value
> # or something like that...
>
> class B(object):
> foo = A('foo')
Thanks, this seems to be the less "magical" solution. I don't like having
to repeat the attribute name, but nothing is perfect...
And thanks to Rainer Mansfeld too; looking up the matching attribute may
be useful in other cases.
--
Gabriel Genellina
More information about the Python-list
mailing list