【问题标题】:Are __eq__, __ne__, __hash__ attributes of object type?__eq__、__ne__、__hash__ 是对象类型的属性吗?
【发布时间】:2017-06-02 11:47:23
【问题描述】:

在下面的属性列表中,

>>> 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__', ...]
>>>

并且objectis-a 不在type 关系中

>>> 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的属性吗?

【问题讨论】:

  • typeobject 的“元类”。 :)
  • isinstance(object, type) 返回True
  • @OluwafemiSule 嗯 1) isinstance(X, type) 也返回 true。 object 不是 type 的子类,但 Xtype 的子类。这里发生了什么? 2)X为什么要继承type的属性

标签: python


【解决方案1】:

type 中的方法定义类的行为方式,object 中的方法实现实例的行为方式。

使用object 的子类:

class X(object):
    pass

然后

X == X

将致电type.__eq__(X, X)

但是:

X() == X()

将致电object.__eq__(X, X)

至少只要您不覆盖这些magic methods(直接在您的X 中或在您为X 定义自己的元类时)。


如果您“使用元”,那么重要的是要知道元类之于类就像实例之于类:

>>> isinstance(object, type)   # class & metaclass
True

>>> isinstance(X(), X)         # instance & class
True

【讨论】:

    【解决方案2】:

    它们是数据模型定制的一部分,称为“魔术方法”,您必须将它们视为与 python 功能交互的接口。 这是所有与此相关的documentation

    【讨论】:

      猜你喜欢
      • 2011-03-05
      • 2017-03-14
      • 2016-09-19
      • 2020-08-28
      • 1970-01-01
      • 2018-09-13
      • 2011-05-20
      • 2019-11-30
      • 2015-08-01
      相关资源
      最近更新 更多