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

spir denis.spir at gmail.com
Thu Jan 2 17:21:46 CET 2014


On 01/02/2014 02:40 PM, Steven D'Aprano wrote:
> On Thu, Jan 02, 2014 at 11:12:30AM +0100, spir wrote:
>> Hello tutorians,
>>
>> 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?
>
> py> type(42).__name__
> 'int'
> py> class Spam:
> ...     pass
> ...
> py> Spam.__name__
> 'Spam'
>
>
>> The point is to have a super-type define a general __repr__ like eg:
>>
>> class SuperType:
>>      # ...
>>      def __repr__ (sef):
>>          return "%s(stuff)" % (self.__class__.__name__, stuff)
>
> That works for me. Is there some reason you think it doesn't work?

Sorry again, the reason is dir() does not show __name__ for classes, while it 
does for funcs. See answer to Dominik. I guess I've now found it:

>>> class C: pass
...
>>> dir(C) 		# note __dir__ below:
['__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__']
>>> dir(C.__dir__)	# here is __name__ :
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', 
'__init__', '__le__', '__lt__', '__name__', '__ne__', '__new__', '__objclass__', 
'__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
'__sizeof__', '__str__', '__subclasshook__']

Denis


More information about the Tutor mailing list