Java dev
Java dev

Reputation: 89

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?

Upvotes: 8

Views: 26589

Answers (2)

Les
Les

Reputation: 10605

When you compare with less-than, __lt__(other) is called with with a DNA object. When you call __init__, self.seq is set to a string (str). So, you are comparing a str < DNA object.

Magic method are magic, not clairvoyant. They won't know what you intend the comparison to be, so it will use what it will use a default (probably the output of repr(), I didn't check).

You need to specify your design what makes one DNA equal to another. Your code implies that the sequence length determines equality. So different sequences can be computed as being equal. Your equality method therefore implies that a sequence is less than another when it is shorter. So your method might be better written by comparing the lengths of the sequences rather the str to DNA object.

Upvotes: 0

Pavel Anossov
Pavel Anossov

Reputation: 62948

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.

Upvotes: 19

Related Questions