gpt4 book ai didi

python - 是否可以使用 __rmod__ 覆盖 str 的 % 行为?

转载 作者:太空狗 更新时间:2023-10-29 22:29:07 25 4
gpt4 key购买 nike

我想做的事:

x %doSomething% y

除了 x 是 str 的情况外,对于任何 x 和任何 y,这很容易做到(参见下面的代码)。

有什么方法(例如添加特殊方法或引发特定错误)导致旧样式字符串格式化失败(类似于 1 %doSomthing 失败并出现 TypeError)并恢复到 doSomething 对象中定义的 __rmod__ 方法?

class BinaryMessage(object):
def __init__(self, fn):
self._fn = fn
def __rmod__(self, LHS):
return BinaryMessagePartial(self._fn, LHS)

class BinaryMessagePartial(object):
def __init__(self, fn, LHS):
self._fn = fn
self._LHS = LHS
def __mod__(self, RHS):
return self._fn(self._LHS, RHS)

def _doSomething(a , b):
return a + b

doSomething = BinaryMessage(_doSomething)

result = 5 %doSomething% 6
assert result == 11

最佳答案

注意:我提交了 Python 2.7、3.5 及更高版本的补丁。这些已经登陆并成为 2.7.14、3.5.4、3.6.1 和 3.7 的一部分,其中 OP 示例现在可以按预期工作。对于旧版本,请参见下文。


不幸的是,目前这在 Python 中是不可能的。该行为在评估循环中被硬编码:

TARGET(BINARY_MODULO) {
PyObject *divisor = POP();
PyObject *dividend = TOP();
PyObject *res = PyUnicode_CheckExact(dividend) ?
PyUnicode_Format(dividend, divisor) :
PyNumber_Remainder(dividend, divisor);

(从 Python 3.5 source code 开始,其中 PyUnicode 是 Python str 类型)。

这很不幸,因为对于所有其他类型,您可以通过为右侧操作数使用子类来阻止调用LHS.__mod__ 方法;来自 documentation :

Note: If the right operand’s type is a subclass of the left operand’s type and that subclass provides the reflected method for the operation, this method will be called before the left operand’s non-reflected method. This behavior allows subclasses to override their ancestors’ operations.

这将是这里唯一的选择,str % other 永远不会返回 NotImplemented所有 RHS 类型都被接受(仅实际的 str.__mod__ method接受 RHS 的 str 对象,但在这种情况下不被调用。

我认为这是 Python 中的一个错误,归档为 issue #28598

关于python - 是否可以使用 __rmod__ 覆盖 str 的 % 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40402235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com