how to dynamically generate __name__ for an object?

Fuzzyman fuzzyman at gmail.com
Wed Aug 10 18:38:07 CEST 2011


On Aug 10, 4:25 pm, Ian Kelly <ian.g.ke... at gmail.com> wrote:
> On Wed, Aug 10, 2011 at 8:48 AM, Fuzzyman <fuzzy... at gmail.com> wrote:
> > __name__ can be a descriptor, so you just need to write a descriptor
> > that can be fetched from classes as well as instances.
>
> > Here's an example with a property (instance only):
>
> >>>> class Foo(object):
> > ...   @property
> > ...   def __name__(self):
> > ...     return 'bar'
> > ...
> >>>> Foo().__name__
> > 'bar'
>
> But:
>
> >>> Foo.__name__
> 'Foo'

That's why I said "you just need to _write_ a descriptor that can be
fetched from classes as well as instances". The example with property
was to show that it *could* be a descriptor. You can write descriptors
with custom behaviour when fetched from a class.

However it turns out that you're right and I'm wrong; __name__ is
special:

>>> class descriptor(object):
...  def __get__(*args):
...   return 'bar'
...
>>> class Foo(object):
...  __name__ = descriptor()
...
>>> Foo.__name__
'Foo'
>>> Foo().__name__
'bar'
>>> class Foo(object):
...  name = descriptor()
...
>>> Foo.name
'bar'

As Eric points out in his original slot, types have their __name__
slot filled in with a string in typeobject.c

All the best,

Michael
--
http://voidspace.org.uk/



More information about the Python-list mailing list