繁体   English   中英

python%s字符串替换和“ self”?

[英]python %s string substitution and “self”?

在pyyaml doc中看到此代码,为什么"Dice(%s,%s)" % self有效? 有两个%s但只有一个var self

>>> class Dice(tuple):
...     def __new__(cls, a, b):
...         return tuple.__new__(cls, [a, b])
...     def __repr__(self):
...         return "Dice(%s,%s)" % self

>>> print Dice(3,6)
Dice(3,6)

http://pyyaml.org/wiki/PyYAMLDocumentation#Constructorsrepresentersresolvers

Dice是从tuple派生的类,它是长度为2的tuple

您可以看到例如

>>> print yaml.dump(Dice(3,6))

!!python/object/new:__main__.Dice
- !!python/tuple [3, 6]

因此,在您的上下文中,它运行良好,确实是长度为2的元组,因此可以解析所使用的字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM