__repr__ method appears can't be invoked automatically for Exception class

Ste*_*ong 5 python python-3.x

I was told that if an obj's __str__ method isn't created but __repr__ is created then printing the obj will invoke __repr__. That appears to be true for normal class, but when I try it on Exception's subclass, it is weird that __repr__ doesn't get invoked, could anyone explain why?

Here's an example

class BoringError(Exception):
  def __init__(self):
    self.purpose = "Demonstration"
    self.boringLevel = 10
  def __repr__(self):
    return "I'm a message for developer"

 try: 
   if 1 != 2:
    raise BoringError 
 except BoringError as e:
   print(e.boringLevel)
   print(e)

class Tree:
  def __repr__(self):
    return "I love water"

AVL = Tree()
print(AVL)
Run Code Online (Sandbox Code Playgroud)

This program produces the following result

10

I love water
Run Code Online (Sandbox Code Playgroud)

Instead of

10
I'm a message for developer
I love water
Run Code Online (Sandbox Code Playgroud)

che*_*ner 4

__repr__仅当解析为e.__str__时才被调用object.__str__,其基本定义如下

def __str__(self):
    return self.__repr__()
Run Code Online (Sandbox Code Playgroud)

在您的情况下,object.__str__永远不会被调用,因为e.__str__解析为Exception.__str__,它不会调用的任何定义__repr__。比较:

>>> e = Exception("hi")
>>> print(e)
hi
>>> str(e)
'hi'
>>> repr(e)
"Exception('hi')"
Run Code Online (Sandbox Code Playgroud)

Tree.__str__未定义,因此解析为,因此AVL.__str__ 调用。object.__str__Tree.__repr__