[英]__eq__ on super objects
以下代碼在Python 3(3.5.2)中工作正常,但引發AttributeError: 'super' object has no attribute '__eq__'
在Python 2(2.7.12)中AttributeError: 'super' object has no attribute '__eq__'
class Derived(int):
def __eq__(self, other):
return super(Derived, self).__eq__(other)
a, b = Derived(1024), Derived(1729)
print(a == b)
預期會出現Python 3行為。 我試圖理解為什么它在Python 2中不起作用。
請注意,此問題不是'super'對象的重復項, 沒有屬性'__eq__'
這里發生的是Derived
的超類是int
。 在Python 2中, int
不會實現__lt__
, __gt__
或__eq__
類的豐富比較運算符,因為它使用__cmp__
代替。 但是,Python 3不支持__cmp__
,因此int
在Python 3中實現了豐富的比較運算符,如__lt__
, __gt__
和__eq__
。因此,在Python 2 Derived
中, super.__eq__
不存在,因為int.__eq__
在Python中不存在。 2。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.