gpt4 book ai didi

python - 如果 `__radd__` 引发 `__add__`,是否调用 `NotImplementedError`?

转载 作者:太空宇宙 更新时间:2023-11-04 11:08:40 26 4
gpt4 key购买 nike

假设我们写一个小类:

class K:
pass
obj = K()

是下面的代码...

total = 4 + obj

...本质上和下面一样?

import io
try:
total = 4.__add__(obj)
except NotImplementedError:
try:
total = obj.__radd__(4)
except AttributeError:
# type(obj) does not have an `__radd__` method
with io.StringIO() as string_stream:
print(
"unsupported operand type(s) for +:",
repr(type(4).__name__),
"and",
repr(type(obj).__name__),
file=string_stream
) # `repr` puts quotes around the type names
msg = string_stream.getvalue()
raise TypeError(msg) from None

最佳答案

触发 __radd__() 的行为实际上不是 NotImplementedError,而是一个名为 NotImplemented 的特殊对象:

>>> help(NotImplemented)
Help on NotImplementedType object:

class NotImplementedType(object)
| Methods defined here:
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.

NotImplementedError 仍将作为错误传播。但是,返回 NotImplemented 对象(而不是引发错误)将允许 __radd__() 触发:

>>> class A:
... def __add__(self, other):
... raise NotImplementedError()
...
>>> class B:
... def __add__(self, other):
... print("__add__ was called")
... def __radd__(self, other):
... print("__radd__ was called")
...
>>> class C:
... def __add__(self, other):
... return NotImplemented
...
>>> a, b, c = A(), B(), C()
>>> b + a
__add__ was called
>>> a + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __add__
NotImplementedError
>>> b + c
__add__ was called
>>> c + b
__radd__ was called

关于python - 如果 `__radd__` 引发 `__add__`,是否调用 `NotImplementedError`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58828522/

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