蟒蛇运算符重载(python overloading operators)

2019-07-21 19:39发布

我需要实现其具有的属性它由字符从字母(“A,C,G,T”)的字符串的序列的DNA类和我需要重载一些运营商如小于,大于,等。

这里是我的代码:

class DNA:
    def __init__(self,sequence):
        self.seq=sequence

    def __lt__(self,other):
        return (self.seq<other)

    def __le__(self,other):
        return(self.seq<=other)

    def __gt__(self,other):
        return(self.seq>other)

    def __ge__(self,other):
        return(len(self.seq)>=len(other))

    def __eq__(self,other):
        return (len(self.seq)==len(other))

    def __ne__(self,other):
        return not(self.__eq__(self,other))

    dna_1=DNA('ACCGT')
    dna_2=DNA('AGT')
    print(dna_1>dna_2)

问题:

当我print(dna_1>dna_2)返回false的,而不是true ,为什么?

Answer 1:

你可能想比较seq S:

def __lt__(self, other):
    return self.seq < other.seq

etc.

没有selfseqotherselfseqotherseq

other这里是另一个DNA。

如果你需要比较长:

def __lt__(self, other):
    return len(self.seq) < len(other.seq)

etc.


文章来源: python overloading operators