1

Is there a way to get the name of a class at class level in Python?

Minimum working example:

class TestClass:

    print("We are now in the class {} at class level".format(WHAT SHOULD I PUT HERE?))  # Should return "We are now in the class TestClass at class level"
    pass
petezurich
  • 9,280
  • 9
  • 43
  • 57
Adriaan
  • 715
  • 10
  • 22

3 Answers3

6

Here's how you can find out:

class TestClass:
    print(locals())

This prints:

{'__module__': '__main__', '__qualname__': 'TestClass'}

So you can use __qualname__, i.e.

class TestClass:
    print("We are now in the class {} at class level".format(__qualname__))
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
0

For defined classes only: Use type(self).__name__ where .__name__ is a default attribute.

Refer to @Alex Hall's answer for using the class name before __init__ takes place, using locals().

Ajit Panigrahi
  • 752
  • 10
  • 27
0

This works :

class Test :
   CLASSNAME = locals()['__qualname__']

Use the CLASSNAME variable anywhere in the class or outside.