【问题标题】:python %s string substitution and "self"?python %s 字符串替换和“self”?
【发布时间】:2016-06-13 01:35:10
【问题描述】:

在 pyyaml 文档中查看此代码,为什么 "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

【问题讨论】:

  • 因为self 是一个包含两个项目的tuple
  • 啊……对。谢谢!
  • ekhumoro - 听起来你应该将此作为答案而不是评论 - 并因此而受到赞誉。

标签: python repr string-substitution


【解决方案1】:

Dicetuple的派生类,它是一个长度为2的tuple

你可以看到例如

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    相关资源
    最近更新 更多