Getting a class name

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Feb 18 18:54:01 EST 2007


Gabriel Genellina a écrit :
> En Sun, 18 Feb 2007 14:14:41 -0300, goodwolf <Robert.Katic at gmail.com>  
> escribió:
> 
>> On Feb 18, 9:17 am, "Gabriel Genellina" <gagsl... at yahoo.com.ar> wrote:
>>
>>> En Sun, 18 Feb 2007 04:20:33 -0300, goodwolf <Robert.Ka... at gmail.com>
>>> escribió:
>>>
>>> > I suppose that you wont get class name into its code (or before
>>> > definition end) but not into a method definition.
>>>
>>> > import sys
>>>
>>> > def getCodeName(deap=0):
>>> >     return sys._getframe(deap+1).f_code.co_name
>>>
>>> > class MyClass (object):
>>> >     name = getCodeName() + '!'
>>>
>>> What's the advantage over MyClass.__name__?
>>>
>>> -- 
>>> Gabriel Genellina
>>
>>
>>>>> class C(object):
>>
>> ...     name = C.__name__
>> ...
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in ?
>>   File "<stdin>", line 2, in C
>> NameError: name 'C' is not defined
>>
>>>>>
> 
> I were asking, why do you want a "name" attribute since "__name__" 
> already  exists and has the needed information. And worst, using an 
> internal  implementation function to do such task.
> 
This might be useful to avoid metaclass hacks when trying to initialize 
a class attribute that would require the class name. (my 2 cents)



More information about the Python-list mailing list