gpt4 book ai didi

python - 我如何从 minimock 中的模拟方法访问对象的 "self"

转载 作者:行者123 更新时间:2023-11-28 21:05:38 27 4
gpt4 key购买 nike

在 Python 中,我想使用 minimock 库模拟类的 __init__ 方法。

这是解释器所做的(ipython):

In [1]: import minimock

In [2]: class A:
...: def __init__(self):
...: print "REAL INIT"
...:

In [3]: def new_init(self):
...: print "NEW INIT"
...:

In [4]: minimock.mock("A.__init__", returns_func=new_init)

In [5]: a = A()
Called A.__init__()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-144b248f218a> in <module>()
----> 1 a = A()

D:\Tools\Python27\lib\site-packages\minimock\__init__.pyc in __call__(self, *args, **kw)
492 if self.mock_tracker is not None:
493 self.mock_tracker.call(self.mock_name, *args, **kw)
--> 494 return self._mock_return(*args, **kw)
495
496 def _mock_return(self, *args, **kw):

D:\Tools\Python27\lib\site-packages\minimock\__init__.pyc in _mock_return(self, *args, **kw)
505 raise Exception("No more mock return values are present.")
506 elif self.mock_returns_func is not None:
--> 507 return self.mock_returns_func(*args, **kw)
508 else:
509 return None

TypeError: new_init() takes exactly 1 argument (0 given)

但是,如果我从 new_init 中删除 self 参数:

def new_init():
print "NEW INIT"

实例化 A 类给出:

In [13]: a = A()
Called A.__init__()
NEW INIT

这让我认为 minimock 对“ self ”有限制。

你知道是否可以在传递给 minimock 的方法的模拟版本中使用“self”吗?

最佳答案

我真的不明白你为什么要这样做,无论如何答案是你不应该直接调用 A.__init__:

>>> class A(object):
... def __init__(self):
... print('Old init - self' + str(self))
>>> def new_init(self):
... print('New init - self:' + str(self))
...
>>> A.__init__ = new_init
>>> A.__init__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method new_init() must be called with A instance as first argument (got nothing instead)
>>> A()
New init - self:<__main__.A object at 0x2446d90>
<__main__.A object at 0x2446d90>

minimock 库没有做错任何事。 __init__ 是通过调用类来调用的。如果您显式调用它,那么您必须显式传递一个实例作为第一个参数。

无论如何,我强烈建议您重新考虑一下您正在做的事情,因为您不应该做这样的事情。模拟应该用于模拟整个对象,而不仅仅是一个方法。在你的情况下,我会模拟整个类 A 而不仅仅是它的 __init__ 方法。

关于python - 我如何从 minimock 中的模拟方法访问对象的 "self",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14463159/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com