[英]Are __eq__, __ne__, __hash__ attributes of object type?
在下面的屬性列表中,
>>> dir(object)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
__eq__
, __ne__
& __hash__
未示出作為屬性。 它們是元類type
屬性
>>> dir(type)
[... '__eq__', .... '__hash__', ... '__ne__', ...]
>>>
並且object
不在is-a
與type
is-a
關系
>>> issubclass(object, type)
False
>>> issubclass(type, object)
True
但是,我看到這些屬性是object
一部分,
>>> object.__eq__
<method-wrapper '__eq__' of type object at 0x905b80>
>>> object.__ne__
<method-wrapper '__ne__' of type object at 0x905b80>
>>> object.__hash__
<slot wrapper '__hash__' of 'object' objects>
>>>
這允許,
class X(object):
pass
class X
來覆蓋這些屬性。
題:
這些是object
屬性嗎?
type
的方法定義類的行為, object
的方法實現實例的行為。
使用object
的子類:
class X(object):
pass
然后
X == X
將調用type.__eq__(X, X)
但:
X() == X()
將調用object.__eq__(X, X)
至少只要不覆蓋這些魔術方法 (無論是直接在X
還是在為X
定義自己的元類時)。
如果您“去meta”,那么重要的是要知道元類是類,實例是類:
>>> isinstance(object, type) # class & metaclass
True
>>> isinstance(X(), X) # instance & class
True
它們是數據模型定制的一部分,稱為“魔術方法”,您必須將它們視為與python功能交互的接口。 這是與此有關的所有文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.