簡體   English   中英

__eq__關於超級對象

[英]__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.

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