如何确定类彼此不相等

问题描述 投票:0回答:1

我不确定如何确定从其他类继承的类不相等。

我曾尝试使用isinstance来执行此操作,但是我对此方法并不精通。

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))

因此,在主方法中,它说要打印(Chicken(2.1)== Duck(2.1))并打印True,但是由于它们是不同的类,因此我希望它返回False。任何帮助将不胜感激。

python
1个回答
1
投票

您可以在__eq__中定义FarmAnimal方法,并检查self的类是否也与other的类相同:

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

并且您不必在子类中编写特定的__eq__方法。

© www.soinside.com 2019 - 2024. All rights reserved.