【发布时间】:2013-09-26 15:51:48
【问题描述】:
str.__mod__ 的确切行为是否记录在案?
这两行代码按预期工作:
>>> 'My number is: %s.' % 123
'My number is: 123.'
>>> 'My list is: %s.' % [1, 2, 3]
'My list is: [1, 2, 3].'
这条线的行为也符合预期:
>>> 'Not a format string' % 123
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
但是这条线是做什么的,为什么它没有引发任何错误?
>>> 'Not a format string' % [1, 2, 3]
'Not a format string'
P。
>>> print(sys.version)
3.3.2 (default, Aug 15 2013, 23:43:52)
[GCC 4.7.3]
【问题讨论】:
-
请注意,这种行为在 Python 3.8 中仍然存在,并且似乎只有 list 或 dict 参数无法产生错误。
-
range()也无法产生错误(至少在 Python 3.7.3 中),但生成器表达式会产生错误。看起来很神秘 -
奇怪的是,没有字典、列表和范围都有的神奇方法,但元组(抛出错误)缺乏。另一方面,字典、列表和范围都实现了
'__iter__', '__len__', '__contains__', '__getitem__',但简单的数字却没有——所以我怀疑其中一种方法与观察到的行为有关。 -
@JohnColeman 查看我的回答。通常所有可以 sed 为“映射”并且可以被索引的 args 都不会引发错误,但
tuples 被明确排除,可能是因为它们用于 varargs 解包。 -
@JanChristophTerasa 这是一个不错的答案 (+1)。作为一个快速测试,我刚刚编写了一个包含
def __getitem__(self): pass的单行定义的类,并且该类的一个对象按照您的回答表明它应该起作用。元组在这里自动解包因此被排除在外是有道理的。
标签: python list modulo string-interpolation python-3.2