使用重载的比较运算符从int派生类访问原始int比较

abu*_*kaj 5 python inheritance operator-overloading comparison-operators python-2.7

我有一个带有重载比较运算符的int派生类.

在重载方法的主体中,我需要使用原始运算符.

玩具示例:

>>> class Derived(int):
...     def __eq__(self, other):
...         return super(Derived, self).__eq__(other)
Run Code Online (Sandbox Code Playgroud)

使用Python 3.3+可以正常工作,但是在Python 2.7中有例外AttributeError: 'super' object has no attribute '__eq__'.

我可以考虑几个walkarrounds,我觉得不是很干净:

return int(self) == other
Run Code Online (Sandbox Code Playgroud)

需要创建一个新int对象,只是为了比较它

try:
    return super(Derived, self).__eq__(other)
except AttributeError:
    return super(Derived, self).__cmp__(other) == 0
Run Code Online (Sandbox Code Playgroud)

基于Python版本拆分控制流,我觉得非常混乱(因此明确地检查Python版本).

如何使用Python 2.7和3.3+以优雅的方式访问原始整数比较?

Gre*_*220 0

我相信你应该__eq__int定义类之前定义。例如:

int = 5
def int.__eq__(self, other):
    return self.real == other
IntDerived = Derived(int)
Run Code Online (Sandbox Code Playgroud)

这应该给super类一个__eq__属性。


编辑


主要想法是有效的,但我注意到代码不起作用。所以:改进的代码:

class Derived(int):
    def __eq__(self, other):
        return self.real == other

Int = 5
D = Derived(Int)
D.__eq__(4) #Output: False
D.__eq__(5) #Output: True
Run Code Online (Sandbox Code Playgroud)