簡體   English   中英

是對象類型的__eq__,__ne__,__hash__屬性嗎?

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

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