异常子类的 args 属性类型从字符串更改为元组

AI0*_*867 5 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")
Run Code Online (Sandbox Code Playgroud)

这导致:

<type 'str'>
<type 'tuple'>
<type 'tuple'>
Error('f', 'o', 'o')
Run Code Online (Sandbox Code Playgroud)

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

args 参数的名称是不相关的。只要将其分配给 self.args,将其更改为“a”就会产生相同的行为。

hap*_*ave 4

查看您链接到的代码,有一个为“args”属性定义的设置器。查找 BaseException_set_args - 它被设置为(链接代码中的其他位置)作为 args 的设置器。因此,当您编写 时self.args = args,您实际上是在调用函数 BaseException_set_args,并将args其作为参数。

如果您随后查看 BaseException_set_args,它会将参数强制转换为元组。如果您尝试将 self.args 设置为无法转换为元组的内容(例如 try Error(23)),您将收到 TypeError 。