【发布时间】:2022-01-14 09:56:19
【问题描述】:
我有一个主要的“抽象”类 Pet,以及两个“真实”类 Dog 和 Cat。当我有两个宠物实例时,我想知道它们是否是“同一种宠物”,而不用关心它们是什么类型的宠物。
我试过了
#!/usr/bin/python
class Pet:
name = "pet"
def __eq__(self, other):
return type(self) == type(other)
# return type(self).__name__ == type(other).__name__
# return self.__class__ == other.__class__
# return self.__class__.__name__ == other.__class__.__name__
# return self.__class__ is other.__class__
# return self.__class__.__name__ is other.__class__.__name__
# return isinstance(other, type(self).__name__)
# return isinstance(other, type(self))
# return isinstance(self, type(other).__name__)
# return isinstance(self, type(other))
# return type(self) is type(other)
# return type(self).__name__ is type(other).__name__
class Dog:
name = "dog"
class Cat:
name = "cat"
dog1 = Dog()
dog2 = Dog()
cat1 = Cat()
cat2 = Cat()
print("dog1 == dog2: {0}".format(dog1 == dog2))
print("cat1 == cat2: {0}".format(cat1 == cat2))
print("cat1 == dog1: {0}".format(cat1 == dog1))
我尝试了所有注释返回,它总是给出这个结果:
$ ./test.py
dog1 == dog2: False
cat1 == cat2: False
cat1 == dog1: False
我猜是因为它将第一个操作数视为Pet,因为该方法在此类中。
有没有办法在主类中进行这样的测试以避免代码重复?
编辑:
正如多人提到的那样,它忘记了子类化部分...
这按预期工作
#!/usr/bin/python
class Pet:
name = "pet"
def __eq__(self, other):
return self.__class__ == other.__class__
class Dog(Pet):
name = "dog"
class Cat(Pet):
name = "cat"
【问题讨论】:
-
您是否打算创建
Pet的Dog和Cat子类?Pet目前在此代码中没有任何用途。 -
停止使用
class.__name__ -
为什么不 dog1.name ==cat1.name ?你也可以做 type(dog1) == type(cat1)
-
如果你使用 f-strings 而不是
format,它也更具可读性。 -
如果您没有忘记子类化,您的代码将起作用。将您的类定义为
class Dog(Pet):和class Cat(Pet):。最重要的是:猫总是先于狗(我的猫说)。
标签: python polymorphism instance