Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

python overloading operators

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...