2016-02-29 43 views
0

在pyyaml doc中查看此代码,为什么"Dice(%s,%s)" % self有效?有两个%s但只有一个变量selfpython%s字符串替换和“自我”?

>>> 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

+10

因为'self'是包含两个项目的'tuple'。 – ekhumoro

+0

啊......对。谢谢! – Shuman

+0

ekhumoro - 听起来像你应该让这个答案,而不是评论 - 并被记入它。 –

回答

0

Dicetuple派生类,它是一种长度tuple 2.

你可以看到的例子,

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

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

所以在您的上下文,它工作得很好,它确实是长度为2的元组,所以可以解析使用的字符串。