Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 异常子类';s类型从字符串更改为元组_Python - Fatal编程技术网

Python 异常子类';s类型从字符串更改为元组

Python 异常子类';s类型从字符串更改为元组,python,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") 这导致:

这在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')

错误('f','o','o')
出于某种原因,args属性被强制转换为一个元组。 它是在C中定义的这一事实可能与此有关吗


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

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

如果然后查看BaseException\u set\u args,它将参数强制转换为元组。如果您将try to set self.args设置为无法转换为元组的内容(例如try
Error(23)
),您将得到一个TypeError