[Tutor] what's your name? (to a class)

spir denis.spir at gmail.com
Thu Jan 2 17:18:04 CET 2014


On 01/02/2014 11:18 AM, Dominik George wrote:
> Hi,
>
>> Am I missing something or don't classes know how they're called
>> (unlike funcs, which have a __name__ attribute, very practicle)? Is
>> there a way to get it otherwise?
>
> The class has it, the instance doesn't. That said, you are looking for self.__class__.__name__ ...
>
>> class SuperType:
>>      # ...
>>      def __repr__ (sef):
>>          return "%s(stuff)" % (self.__class__.__name__, stuff)
>
> ... which you do use here.

Well, this was not real code, but an example of what I wished to be able to write!

>> But I need each class to know its name. Subtypes are actually
>> defined by users (of a lib), presently they are forced to write the
>> name explicitely, which is stupid since they already give it as var
>> name:
>>
>> class SubType (SuperType):
>>      __name__ = "SubType"
>>      # ....
>
> I do not get it. The __class__.__name__ thing works great for me:
>
>    >>> class Foo():
>    ...     def whoami(self):
>    ...         return self.__class__.__name__
>    ...
>    >>> f = Foo()
>    >>> f.whoami()
>    'Foo'
>    >>> class Bar(Foo):
>    ...     pass
>    ...
>    >>> b = Bar()
>    >>> b.whoami()
>    'Bar'
>
> Please be a bit more specific about your problem, because the problem
> you described obviously does not exist ;).

I just missed it. Sorry!
In fact, I did:

>>> class C: pass
...
>>> dir(C)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', 
'__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', 
'__subclasshook__', '__weakref__']

No __name__, or am I blind? But:

>>> C.__name__
'C'

Still, there is a __name__.
???


Compare with:

>>> def f(): pass
...
>>> dir(f)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', 
'__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', 
'__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', 
'__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', 
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Here I can see __name__ (thus, I'm probably not that blind yet ;-).

Denis



More information about the Tutor mailing list