python元组和列表.一个拒绝转换的元组

Jas*_*ase 5 python tuples list python-2.7 iterable-unpacking

我需要知道为什么这会失败:

class ConfigurationError(Exception):
    def __init__(self, *args):
        super(ConfigurationError, self).__init__(self, args)

        self.args = list(args)
        # Do some formatting on the message string stored in self.args[0]
        self.args[0]=self.__prettyfi(self.args[0])

    def __prettyfi(self, arg):
        pass
        # Actual function splits message at word
        # boundaries at pos rfind(arg[1:78]) if len(arg) >78
        # it does this by converting a whitespace char to a \n
Run Code Online (Sandbox Code Playgroud)

当我运行代码时,我收到以下消息: <snip> ConfigurationError.py", line 7, in __init__ self.args[0]=self.__prettyfi(self.args[0]) TypeError: 'tuple' object does not support item assignment

我编辑了第一行.匹配此代码示例.

我不明白为什么self.args = list(args)没有正确地将元组解压缩到第5行的列表中.

(我有一种潜行的怀疑,我没记得超基本的东西...)

Mar*_*ers 11

Exception.args描述符 ; 它挂钩__set__将您指定的任何内容self.args转换为元组.

因此,只要将列表分配给self.args,描述符就会将其转换回元组.这并不是说你的list()电话失败了,这Exception.args就是特别的.

BaseException.args 记录为元组,在Python 2中,异常对象支持切片:

>>> ex = Exception(1, 2)
>>> ex.args
(1, 2)
>>> ex[0]
1
Run Code Online (Sandbox Code Playgroud)

例外也应该是不可改变的; 保持.args属性为元组有助于保持它们.此外,__str__异常的处理程序期望.args是一个元组,并将其设置为其他东西导致过去的奇怪错误.

  • @Tinctorius:异常是不可变的,`args`也必须是.而且,`Exception.args`被记录为元组. (3认同)
  • 它是描述符有什么技术原因吗? (2认同)