Python 异常子类';s类型从字符串更改为元组
这在python2.6和python3上都会发生: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") 这导致:
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设置为无法转换为元组的内容(例如tryError(23)
),您将得到一个TypeError