python overloading operators

橙三吉。 提交于 2019-11-30 17:13:16

问题


I need to implement a DNA class which has attribute a sequence which consists of a string of characters from the alphabet ('A,C,G,T') and I need to overload some operators like less than,greater than,etc..

here is my code:

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)

PROBLEM:

when I print(dna_1>dna_2) it returns false instead of true... Why ?


回答1:


You probably want to compare seqs:

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

etc.

Not self's seq with other, self's seq with other's seq.

other here is another DNA.

If you need to compare lengths:

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

etc.


来源:https://stackoverflow.com/questions/15461574/python-overloading-operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!