在Python3.4中:
>>> import mock.MagicMock
>>> type(mock.MagicMock()) == mock.MagicMock
False # Huh, why is that?
>>> isinstance(mock.MagicMock(), mock.MagicMock)
True
当我将其简化为课程A
和B
时,我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
的
答案 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