【发布时间】:2019-06-19 22:39:52
【问题描述】:
我想要一个 Inf 类,这样我就可以编写类似的代码
>>> class Inf:
... pass # TODO
...
>>> Inf > 3
True
我知道我能做到
>>> class Inf:
... def __gt__(self, other):
... return True
... def __lt__(self, other):
... return False
... def __eq__(self, other):
... return type(self) == type(other)
...
>>> inf = Inf()
>>> inf > 3
True
但我希望类本身能够与ints进行比较,而不是它的实例能够与int进行比较秒。
我希望能够做到Inf > 3 # True,而不是Inf() > 3 # True。
这是我的尝试,没有成功:
>>> class Inf:
... @classmethod
... def __gt__(cls, other):
... return True
... ... # more classmethods
...
>>> Inf > 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: type() < int()
请停!
【问题讨论】:
标签: python-3.x class types operator-overloading