gpt4 book ai didi

python - __repr__ 方法出现无法为 Exception 类自动调用

转载 作者:太空狗 更新时间:2023-10-30 00:52:43 24 4
gpt4 key购买 nike

有人告诉我,如果未创建对象的 __str__ 方法但创建了 __repr__,则打印对象将调用 __repr__。这对于普通类来说似乎是正确的,但是当我在 Exception 的子类上尝试它时,奇怪的是 __repr__ 没有被调用,谁能解释为什么?

举个例子

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)

该程序产生以下结果

10

I love water

代替

10
I'm a message for developer
I love water

最佳答案

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

def __str__(self):
return self.__repr__()

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

>>> e = Exception("hi")
>>> print(e)
hi
>>> str(e)
'hi'
>>> repr(e)
"Exception('hi')"

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

关于python - __repr__ 方法出现无法为 Exception 类自动调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56023376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com