【发布时间】:2019-11-13 00:08:19
【问题描述】:
假设我们写了一个小类:
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
【问题讨论】:
标签: python python-3.x operator-overloading