【问题标题】:Why doesn't __rmod__ work properly for strings? [duplicate]为什么 __rmod__ 不适用于字符串? [复制]
【发布时间】:2017-10-20 17:56:56
【问题描述】:
>>> class MyInt(int):
...     def __rmod__(self, other):
...         return 42
...     
>>> class MyStr(str):
...     def __rmod__(self, other):
...         return 'wat'
...     
>>> 0 % MyInt()
42
>>> '%r' % MyStr()
"''"

为什么int 子类可以从反射面控制这个 BinOp,而str 不能?这似乎与记录在案的datamodel 相矛盾。

我希望使用该功能创建一个非侵入性且向后兼容的扩展,为logging 框架提供花括号样式的处理程序/格式化程序,但这让我停了下来。那是一个错误吗?

Linux 上的 Python 3.6.0。使用collections.UserString 作为基类也有问题。使用bytes 作为基础不会。

【问题讨论】:

  • This 似乎相关。

标签: python python-3.x string-formatting subclassing


【解决方案1】:

这是Python issue 28598。字节码评估循环中% 字符串格式的fast path 未检查字符串子类。它是fixed now,因此请将您的 Python 更新到 v3.6.1+。

【讨论】:

  • 我也将修复程序向后移植到 2.7 和 3.5;它是 2.7.14 和 3.5.4 的一部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
相关资源
最近更新 更多