我很困扰。假设我有一个类(我这样做),其中每个运算符和比较器(+
、-
、<
、>=
、==
等)都返回自身。如果你不明白,这里是代码:
class _:
def __init__(self, *args, **kwargs):
pass
def __add__(self, other):
return self
def __sub__(self, other):
return self
def __mul__(self, other):
return self
def __truediv__(self, other):
return self
def __floordiv__(self, other):
return self
def __call__(self, *args, **kwargs):
return self
def __eq__(self, other):
return self
def __lt__(self, other):
return self
def __gt__(self, other):
return self
def __ge__(self, other):
return self
def __le__(self, other):
return self
我注意到一个不一致的地方。以下工作:
_()+_
_()-_
_()*_
_()/_
_()//_
_()>_
_()<_
_()==_
_()>=_
_()<=_
_<_()
_>_()
_==_()
_<=_()
_>=_()
但以下不是:
_+_()
_-_()
_*_()
_/_()
_//_()
他们给出以下错误:
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'type' and '_'
总而言之,比较器以两种方式使用类型与实例,但运算符仅在实例位于运算符左侧时才起作用。为什么是这样?