1

I read the __str__() vs __repr__() threads, and, somewhere on here (I can't remember where now) I saw the following code:

def __repr__(self):
    return "<%s>" % (self.__class__.__name__)

This obviously prints the class name, so if I have a class like this:

Class A:
    def __repr__(self):
        return "<%s>" % (self.__class__.__name__)

It prints A (I can't make the angle brackets appear?). If I take out the .__name__ bit, it prints <__main__.A> So now I am a little confused, as surely A is the type of Class A, not just its name, and I am not sure where the __main__ bit is coming from as I have no __main__ in the program (yet! - I do know about if __name__ == "__main__" and use it.)

So what is the difference between the Class name and the Class type, and is there ever a situation where they would be different?

Also, just wanted to add, pretty much everything I know about Python I have learnt from SA so far, even tricky questions have answers on here (accessing a superclass class variable from a subclass was my most recent google, and SA was there at number one again!! Thanks everyone!)

marienbad
  • 1,461
  • 1
  • 9
  • 19

1 Answers1

0

You seem to be running the code from within the python interpreter shell. In which case, the __main__ is coming from the shell.

Sample code:

>>> class A:
...     def __repr__(self):
...         return "<%s>" % (self.__class__.__name__)
... 
>>> A()
<A>
>>> class A:
...     def __repr__(self):
...         return "<%s>" % (self.__class__)
...         
... 
>>> A()
<__main__.A>

On class name vs type, you can refer this post -> Python : terminology 'class' VS 'type'

Community
  • 1
  • 1
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186