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
0

3 Answers 3

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__))
Sign up to request clarification or add additional context in comments.

Comments

0

This works :

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

Use the CLASSNAME variable anywhere in the class or outside.

1 Comment

You can just use __qualname__ directly.
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().

2 Comments

@Adriaan is asking how to do it before the __init__, so self is not useable
My bad, updating the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.