python __lt__ __gt__自定义(重载)运算符

时间:2016-06-14 13:58:22

标签: python overloading operator-keyword

通过Python的实验,我来到了代码:

class Chainable(object):
    value = []
    def __init__(self,*args):
        self.value = []
        for a in args:
            if isinstance(a,list):
                self.value += a
            elif isinstance(a,tuple):
                self.value += list(a)
            else: 
                self.value += [a]
        return 

    def __lt__(self,a):
        self.value = [a]+self.value
        return self
    def __gt__(self,a):
        self.value = self.value+[a]
        return self
    def __or__(self,x):
        self.value += [x]
        return self

当我运行这样的代码时:

a = Chainable(1,2,3)

我可以问:a | 4 | 5并收到[1,2,3,4,5]的结果。

但当我要求a > 4 > 5时,我得到的是Falsea = [1,2,3,4]

你能指点一下操作员订购表吗?

1 个答案:

答案 0 :(得分:0)

得到的解决方案(感谢jonrsharpe):

a = Chainable(1,2,3)
a << 0 << -1 >> 4 >> 5
[-1,0,1,2,3,4,5]

并且操作将是这样的:

Location loc = new Location();