有没有一种方法可以比较两个不同的类,如果它们不相同,则返回False

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

我被赋予了不同的农场动物和它们的年龄,我想知道如何比较不同的动物并返回False

我曾尝试返回not __eq__,但似乎无法正常工作。

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 self.age == other.age:
            return True
        else:
            return False

    def __ne__(self, other):
        if self.age is not other.age:
            return True
        else:
            return False

因此,如果给定为Chicken(2) == Duck(2),由于类不同,我想返回False

python-3.x
1个回答
0
投票

您需要显式地键入check,因为否则鸭子式输入(在这种情况下为不幸的名称)意味着具有age且具有相同值的所有内容都相等:

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