簡體   English   中英

如何確定類不相等

[英]How to determine that classes do not equal each other

我不確定如何確定從其他類繼承的類不相等。

我曾嘗試使用 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))

所以在 main 方法中它說 print(Chicken(2.1) == Duck(2.1)) 並且它打印 True,但是因為它們是不同的類,我希望它返回 False。 任何幫助將不勝感激。

您可以在FarmAnimal中定義__eq__方法,檢查self的 class 是否與other的 class 相同:

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

而且您不必在子類中編寫特定的__eq__方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM