为什么type(mock.MagicMock())== mock.MagicMock返回False?

时间:2014-10-11 22:32:16

标签: python-3.x typechecking

在Python3.4中:

>>> import mock.MagicMock
>>> type(mock.MagicMock()) == mock.MagicMock
False # Huh, why is that?
>>> isinstance(mock.MagicMock(), mock.MagicMock)
True

当我将其简化为课程AB时,我type(B()) == B会返回True

>>> class A: pass
>>> class B: pass
>>> class C(A, B): pass
>>> type(B()) == B    
True # Of course I would say. 

为什么要返回type(mock.MagicMock()) == mock.MagicMock False?我知道Python中的difference between isinstance() and type()type()无法“理解”子类化isinstance的位置。但我不明白这是怎么回事。

mock.MagicMock

source

1 个答案:

答案 0 :(得分:3)

更多实验表明答案。

>>> from unittest.mock import MagicMock as mm
>>> mm1 = mm()
>>> mm2 = mm()
>>> type(mm1)
<class 'unittest.mock.MagicMock'>
>>> type(mm2)
<class 'unittest.mock.MagicMock'>
>>> type(mm1) == type(mm2)
False
>>> id(type(mm1))
53511896
>>> id(type(mm2))
53510984
>>> type(mm1) is mm1.__class__
True
>>> mm
<class 'unittest.mock.MagicMock'>
>>> id(mm)
53502776

结论:每个MagicMock实例都有一个&#39;类&#39;看起来像MagicMock,但不是。创建此类实例的是什么? MagicMock子类Mock,它是NonCallableMock的子类,具有 new 方法。

def __new__(cls, *args, **kw):
    # every instance has its own class
    # so we can create magic methods on the
    # class without stomping on other mocks
    new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
    instance = object.__new__(new)
    return instance

new = ...语句创建具有相同名称和docstring的cls参数的子类。下一行创建此子类的单个实例。因此,Mocks遵循修订后的平等而不是type(mm()) is mm

>>> mm.__bases__
(<class 'unittest.mock.MagicMixin'>, <class 'unittest.mock.Mock'>)
>>> type(mm1).__bases__
(<class 'unittest.mock.MagicMock'>,)
>>> type(mm1).__bases__[0] is mm
True