【问题标题】:class that can be compared with ints可以与整数比较的类
【发布时间】: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


    【解决方案1】:

    这几乎是不可能的,因为Inftype 的一个实例,因此您想要比较typeint 的一个实例,所以Inf 的方法__gt__() 在这种情况下是无用的一个案例。 而且我不知道有什么理由避免使用:

    class Inf:
        @classmethod
        def __gt__(cls, other):
            return True
    inf = Inf()
    print(inf > 3)
    

    所以,如果您确实需要比较 class,请尝试编写 type 的子类,它具有覆盖的 __gt__() 方法:

    class MyType(type):
        def __gt__(cls,other):
            return True
    Inf = MyType('Inf',(),{})
    print(Inf > 3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-24
      • 2017-12-03
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 2021-10-26
      相关资源
      最近更新 更多