小编mar*_*wan的帖子

为什么python的异常repr会跟踪传递给__init__的对象?

请看下面的代码片段:

In [1]: class A(Exception):
   ...:     def __init__(self, b):
   ...:         self.message = b.message
   ...: 

In [2]: class B:
   ...:     message = "hello"
   ...: 

In [3]: A(B())
Out[3]: __main__.A(<__main__.B at 0x14af96790>)

In [4]: class A:
   ...:     def __init__(self, b):
   ...:         self.message = b.message
   ...: 

In [5]: A(B())
Out[5]: <__main__.A at 0x10445b0a0>
Run Code Online (Sandbox Code Playgroud)

如果是Afrom 的子类Exception,即使我们只传递了的 message 属性,它也会repr返回一个对 的引用。B()B()

Exception.repr鉴于 cpython 代码不太可读,为什么这是有意的行为,如果可能的话,它如何在 python 伪代码中工作?

python ipython python-3.x

6
推荐指数
1
解决办法
153
查看次数

标签 统计

ipython ×1

python ×1

python-3.x ×1