Skip to content
Advertisement

Python equivalent to Java’s MyClass.class.getName()

In Java, MyClass.class.getName() (assuming a class named ‘MyClass’) serves a purpose of getting the name of ‘MyClass’ even if MyClass is renamed, while hardcoding “MyClass” in a string will become unreliable.

Note: there is no instance available – this is crucial to the question.

e.g., Java:

String unreliableName = "MyClass"; //will be incorrect if 'MyClass' is renamed
String reliableName = MyClass.class.getName(); //if 'MyClass' is renamed, 'reliableName' will still be correct

C# has ‘nameof’, which serves a similar purpose for a much wider range of constructs.

In Python, how would you do this? I think we can rule out the ‘type’ function since we don’t have an instance.

Advertisement

Answer

To get the name of a class, you can use the __name__ variable of the class you want to get the name of.

e.g. A.__name__ for a class called A

For reference: Python Documentation

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement