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
  • 7,683
  • 8
  • 34
  • 51
Adriaan
  • 595
  • 7
  • 21

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
  • 33,530
  • 5
  • 49
  • 82
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
  • 723
  • 11
  • 25
0

This works :

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

Use the CLASSNAME variable anywhere in the class or outside.