异常子类的类型的args属性从string更改为tup

2024-04-16 19:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

在python2.6和python3上都会发生这种情况:

class Error(Exception):
    def __init__(self, args):
            print(type(args))
            print(type(self.args)) # From BaseException
            self.args = args
            print(type(self.args))

Error("foo")

这将导致:

<type 'str'>
<type 'tuple'>
<type 'tuple'>
Error('f', 'o', 'o')

由于某些原因,args属性被强制为元组。 它在C中定义的事实可能与此有关吗?https://github.com/python/cpython/blob/master/Objects/exceptions.c

args参数的名称不相关。将其更改为“a”会导致相同的行为,只要将其分配给self.args. 你知道吗


Tags: fromselffooinitdeftypeexception情况
1条回答
网友
1楼 · 发布于 2024-04-16 19:36:27

查看链接到的代码,有一个为“args”属性定义的setter。查找BaseException\u set\u args-它被设置为args的setter(在链接代码的其他地方)。因此,在编写self.args = args时,实际上是在调用函数BaseException\u set\u args,以args作为参数。你知道吗

如果然后在BaseException\u set\u args中查找,它将参数强制为元组。如果你给我试着设置self.args对于无法转换为元组的内容(例如,tryError(23)),您将得到一个TypeError。你知道吗

相关问题 更多 >