python 元组和列表。拒绝转换的元组

标签 python list python-2.7 tuples 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

当我运行代码时,我收到以下信息: <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 行的列表中。

(我有一种潜移默化的怀疑,我记不住一些超基础的东西……)

最佳答案

Exception.argsdescriptor ;它 Hook __set__将您分配给 self.args任何变成一个元组。

因此,一旦您将列表分配给 self.args,描述符就会将其转换回元组。并不是你的 list() 调用失败了,只是 Exception.args 比较特殊。

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

>>> ex = Exception(1, 2)
>>> ex.args
(1, 2)
>>> ex[0]
1

异常也应该是不可变的;将 .args 属性保留为一个元组有助于保持它们的状态。此外,异常的 __str__ 处理程序期望 .args 是一个元组,并将其设置为其他内容有 led to strange bugs in the past .

关于python 元组和列表。拒绝转换的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14195885/

相关文章:

python - 什么是正确的 : widget. rowconfigure 或 widget.grid_rowconfigure?

asp.net-mvc - viewdata 中的 ASP.NET MVC 通用列表

java - 通用列表的深拷贝

javascript - 从 ASX 页面抓取表格

python - Django 工作人员登录所有网址

python - 使用 South 创建 Django 缓存表?

python - Pandas DataFrames 将方括号添加到特定列值

android - 使用 adb shell 获取 Android 目录中的文件数

python - 如何从Python中的递归函数内部增长并返回列表

python - 将 gspread 与 OAuth2 SignedJwtAssertionCredentials 结合使用