CollegeStruggles
CollegeStruggles

Reputation: 21

How to determine that classes do not equal each other

I am unsure how to determine that classes that inherit from other classes are not equal.

I have tried using isinstance to do this but I am not very well versed in this method.

class FarmAnimal:

    def __init__(self, age):
        self.age = age

    def __str__(self):
        return "{} ({})".format(self, self.age)
from src.farm_animal import FarmAnimal
class WingedAnimal(FarmAnimal):

    def __init__(self, age):
        FarmAnimal.__init__(self, age)

    def make_sound(self):
        return "flap, flap"
from src.winged_animal import WingedAnimal

class Chicken(WingedAnimal):

    def __init__(self, age):
        WingedAnimal.__init__(self, age)

    def __eq__(self, other):
        if self.age == other.age:
            return True
        else:
            return False

    def make_sound(self):
        return WingedAnimal.make_sound(self) + " - cluck, cluck"
from src.chicken import Chicken
from src.winged_animal import WingedAnimal

class Duck(WingedAnimal):

    def __init__(self, age):
        WingedAnimal.__init__(self, age)



    def make_sound(self):
        return WingedAnimal.make_sound(self) + " - quack, quack"

    def __eq__(self, other):
        if not isinstance(other, Duck):
            return NotImplemented
        return self.age == other.age


if __name__ == "__main__":

    print(Chicken(2.1) == Duck(2.1))

So in the main method it says to print(Chicken(2.1) == Duck(2.1)) and it prints True, but because they are different classes, I want it to return False. Any help would be greatly appreciated.

Upvotes: 0

Views: 101

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

You can define your __eq__ method in FarmAnimal, checking if the class of self is the same as the class of other as well:

def __eq__(self, other):
    if self.age == other.age and self.__class__ == other.__class__
        return True
    else:
        return False

and you don't have to write specific __eq__ methods in your subclasses.

Upvotes: 2

Related Questions