0

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.

8
  • 1
    Does this answer your question? How to get the concrete class name as a string? Commented Jul 3, 2021 at 17:49
  • @Lars: No - there is no instance - that's the whole point of the question. Commented Jul 3, 2021 at 17:56
  • The question was closed without carefully reading it - I want the class name without an instance. Commented Jul 3, 2021 at 17:58
  • 2
    The question i linked does not imply that an object is needed. There are good comments on the accepted answer. If you want to get the name of a class called A you can use A.__name__. Commented Jul 3, 2021 at 18:04
  • 1
    Yes, but you can just use the _name_ variable of the class type Commented Jul 3, 2021 at 18:07

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.