反映大于魔术方法

reflected greater than magic methods

我需要一种反映魔法的方法"greater than",但似乎没有。这是情况。我有一个 class 来跟踪单位。是调用属性。我有处理比较的魔术方法设置,但是当我将 属性 放在右侧时它不起作用。这是一个例子:

class Property():
def __init__(self, input, units):
    self.value = input
    self.units = units


def __gt__(self, other):
    if isinstance(other, Property):
        return self.value.__gt__(other.value)
    else:
        return self.value.__gt__(other)

def __float__(self):
    return float(self.value)

if __name__=='__main__':

    x = Property(1.,'kg')
    y = Property(0.,'kg')
    print y > x
    print float(y) > x
    print y > float(x)

所以如果你 运行 你会看到输出是:False, True, False 因为中间的例子正在执行 float > 属性 它使用内置 > 而不是 > 我有使用魔术方法定义。我需要一个当 属性 位于右侧时使用的魔术方法。那不是一回事吗?如果没有,我该如何写这个以便可以比较值的任何组合和我自己的 class 。我不想有任何比较规则。 IE,我不想永远无法将浮点数与 属性 进行比较。

__lt____gt__ 的对应物;您需要实施 __lt__。当你这样做的时候,你可能应该实施 __le____ge__.

既然你已经声明了 __float__() 方法,你总是可以把它写成:

print float(y) > float(x)

您可以使用 functools.total_ordering 装饰器为您创建缺少的比较方法:

import functools

@functools.total_ordering
class Property():
    ...

然后你得到假,假,假。不过,请务必阅读其文档。