如何解决子类和父类的比较
问题
在两个类之间实现比较方法时,结果与预期不符。
class A:
def __init__(self,name: str) -> None:
self.name = name
def __eq__(self,other: object) -> bool:
if not isinstance(other,A):
return NotImplemented
return self.name == other.name
class B(A):
def __init__(self,name: str,value: int) -> None:
super().__init__(name)
self.value = value
def __eq__(self,B):
return NotImplemented
return self.name == other.name and self.value == other.value
a = A("a")
b = B("a",1)
print(a == b) # True
print(b == a) # True
我想要的是这些具有不同属性的类的不同实例是不相等的,所以我希望在这两种情况下都有 False
。
我们得到 True
的原因是因为如果另一个对象不是 B 的实例,我们在 NotImplemented
的 __eq__
方法中返回 B
。这导致要调用的 __eq__
的 A
方法。由于 B
是 A
的子类,isinstance(b,A)
返回 True。
解决方案(尝试 1)
我们可以使用 isinstance(other,A)
代替使用 type(other) is A
进行检查:
class A:
def __init__(self,other: object) -> bool:
if not type(other) is A:
return NotImplemented
return self.name == other.name
class B(A):
def __init__(self,other: object) -> bool:
if not type(other) is B:
return NotImplemented
return self.name == other.name and self.value == other.value
a = A("a")
b = B("a",1)
print(a == b) # False
print(b == a) # False
这按预期工作,但是 mypy 不喜欢它:
error: Returning Any from function declared to return "bool" [no-any-return]
error: "object" has no attribute "name" [attr-defined]
error: Returning Any from function declared to return "bool" [no-any-return]
error: "object" has no attribute "name" [attr-defined]
error: "object" has no attribute "value" [attr-defined]
解决方案(尝试 2)
据我所知,为了让 mypy 喜欢这个解决方案,isinstance
检查必须保留。所以我在值比较中添加了类型检查。
class A:
def __init__(self,A):
return NotImplemented
return self.name == other.name and type(other) is A
class B(A):
def __init__(self,B):
return NotImplemented
return self.name == other.name and self.value == other.value and type(other) is B
a = A("a")
b = B("a",1)
print(a == b) # False
print(b == a) # False
现在mypy对代码没问题了,但是pylint还是不喜欢这个解决方案:
C0123: Using type() instead of isinstance() for a typecheck. (unidiomatic-typecheck)
如何正确解决此问题?
解决方法
你非常接近!
检查两个对象是否使用同一个类的标准过程是这样的:
if type(x) == type(y):
但是,很多 linter 会抱怨并要求您使用 isinstance
,因为他们认为您也希望它对子类的评估结果为 true。你能做的最好的事情就是忽略它们。
希望这能解决您的问题!
编辑:
您应该可以使用 is
而不是 ==
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。