clahey
clahey

Reputation: 4843

How do I get the string with name of a class?

What method do I call to get the name of a class?

Upvotes: 59

Views: 57683

Answers (6)

Azat Ibrakov
Azat Ibrakov

Reputation: 10962

From Python 3.3 and onwards we can use __qualname__ field for both classes & functions.

It differs from __name__ field for nested objects like a class defined in other class

>>> class A:
        class B:
            pass
>>> A.B.__name__
'B'
>>> A.B.__qualname__
'A.B'

which may be quite useful.

Further reading

Upvotes: 10

thayne
thayne

Reputation: 1038

You can also get the name inside the context of the class itself with self.__class__.__name__ or just __class__.__name__.

>>> class A:
...     def __init__(self):
...         # These are equivalent...
...         print(self.__class__.__name__)
...         print(__class__.__name__)
...         print(A.__name__)
... 
>>> a = A()
A
A
A
>>>

Upvotes: 0

Mr Shark
Mr Shark

Reputation: 26468

In [1]: class Test:
   ...:     pass
   ...: 

In [2]: Test.__name__
Out[2]: 'Test'

Upvotes: 71

Jon Cage
Jon Cage

Reputation: 37458

I agree with Mr.Shark, but if you have an instance of a class, you'll need to use its __class__ member:

>>> class test():
...     pass
...
>>> a_test = test()
>>>
>>> a_test.__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute '__name__'
>>>
>>> a_test.__class__
<class __main__.test at 0x009EEDE0>

Upvotes: 13

Reputation:

In [8]: str('2'.__class__)
Out[8]: "<type 'str'>"

In [9]: str(len.__class__)
Out[9]: "<type 'builtin_function_or_method'>"

In [10]: str(4.6.__class__)
Out[10]: "<type 'float'>"

Or, as was pointed out before,

In [11]: 4.6.__class__.__name__
Out[11]: 'float'

Upvotes: 1

clahey
clahey

Reputation: 4843

It's not a method, it's a field. The field is called __name__. class.__name__ will give the name of the class as a string. object.__class__.__name__ will give the name of the class of an object.

Upvotes: 46

Related Questions