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.

Dave Doknjas
  • 6,394
  • 1
  • 15
  • 28
  • 1
    Does this answer your question? [How to get the concrete class name as a string?](https://stackoverflow.com/questions/521502/how-to-get-the-concrete-class-name-as-a-string) – Lars Jul 03 '21 at 17:49
  • @Lars: No - there is no instance - that's the whole point of the question. – Dave Doknjas Jul 03 '21 at 17:56
  • The question was closed without carefully reading it - I want the class name *without an instance*. – Dave Doknjas Jul 03 '21 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__`. – Lars Jul 03 '21 at 18:04
  • @Lars: Doesn't "instance.__class__.__name__" require an instance? – Dave Doknjas Jul 03 '21 at 18:06
  • @Lars: Ok - I see the comment hidden deep in there about A.__name__. I don't think this link directly answers the question - it might be worth a separate question. – Dave Doknjas Jul 03 '21 at 18:07
  • 1
    Yes, but you can just use the \__name\__ variable of the class type – Lars Jul 03 '21 at 18:07
  • @Lars: Could you post the answer? I think anyone looking for this is going to find it a lot easier if it's a separate question. – Dave Doknjas Jul 03 '21 at 18:08

1 Answers1

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

Lars
  • 1,750
  • 2
  • 17
  • 26