为什么不串。格式化程序格式有"self"参数吗?



在阅读python的string模块的源代码时,我对类Formatter感到困惑。

格式化程序类中的format方法(不是静态方法也不是类方法)没有self作为输入参数def format(*args, **kwargs):,但以某种方式直接在方法中使用它。 self, *args = args .

请解释此用法。

class Formatter:
    def format(*args, **kwargs):
        if not args:
            raise TypeError("descriptor 'format' of 'Formatter' object "
                            "needs an argument")
        self, *args = args  # allow the "self" keyword be passed
        try:
            format_string, *args = args # allow the "format_string" keyword be passed
        except ValueError:
            if 'format_string' in kwargs:
                ...
            else:
                ...
        return self.vformat(format_string, args, kwargs)

> self 被假定为 *args 中的第一个arg,并在此行中解压缩:

self, *args = args

在 Python 中声明签名中没有 self 的实例方法是不寻常的。

通过查看方法签名行的 git 历史记录,我们可以看到最初存在self

被删除了,因为如果格式字符串包含名为 self 的变量,例如 'I am my{self}' ,它的存在会导致错误。 引入了从args中解压缩self的异常模式来修复该错误。

错误报告和讨论在这里。

这是错误报告中的错误示例:

>>> string.Formatter().format('the self is {self}', self='bozo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: format() got multiple values for argument 'self'

我假设你熟悉参数中的*args语法。这只是一个任意的未命名参数列表。然后你有

self, *args = args  # allow the "self" keyword be passed

这个评论非常明确。您正在将列表args拆分为第一个元素(我们通常称之为 self ,但只是一个常规参数,始终是对象方法中的第一个),其余的。因此,我们阅读 self ,一切都很好 - 不是立即,而是在函数中。

我能在这里看到的唯一用例来自

if not args:
        raise TypeError("descriptor 'format' of 'Formatter' object "
                        "needs an argument")

这意味着我们期待做这样的事情

Formatter.format(formatterObj,format_string,...)

很多(不知道为什么,像工厂这样的东西?),所以万一我们忘记发送self - formatterObj在我的示例中,我们会收到一个详细的错误。可能是为了支持Formatter对象,这些对象没有format方法,但确实具有vformat方法。不过似乎不太可能。

最新更新