如何在 python 中获得指针类型行为
我想编写一个测试用例来测试函数列表。 这是我想要做的示例:
from mock import Mock
def method1 ():
pass
def method2 ():
pass
## The testcase will then contain:
for func in method_list:
func = Mock()
# continue to setup the mock and do some testing
我想要实现的目标如下:
步骤 1) 将我的本地方法变量分配给 method_list 中的每个项目
步骤 2) 对方法进行 Monkeypatch。在这个例子中,我使用了一个mock.Mock对象,
实际发生的是:
步骤 1) 方法已成功分配给 method_list 中的项目 - OK
然后将步骤 2) 方法分配给对象 Mock() - NOK
在步骤 2 中我想要的是从 method_list 中获取项目,例如 method1 并将其分配给 Mock() 对象。最终结果是 method 和 method1 都指向同一个 Mock() 对象
我意识到我本质上做的是 a = b
a = c
然后期待 c==b !
我想如果不以某种方式获得指向 b 的指针,这实际上是不可能的?
I want to write a test case which will test a list of functions.
Here is an example of what I want to do:
from mock import Mock
def method1 ():
pass
def method2 ():
pass
## The testcase will then contain:
for func in method_list:
func = Mock()
# continue to setup the mock and do some testing
What I want to achieve is as follows:
Step 1) Assign my local method variable to each item in method_list
Step 2) Monkeypatch the method. In this example I am using a mock.Mock object
What actually occurs is:
Step 1) method is successfully assigned to an item from method_list - OK
Step 2) method is then assigned to the object Mock() - NOK
What I wanted in step 2 was to get the item from method_list e.g. method1 to be assigned to the Mock() object. The end result would be that both method and method1 would point to the same Mock() object
I realise that what I am essentially doing is
a = b
a = c
and then expecting c==b !
I guess this is not really possible with out somehow getting a pointer to b ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我理解正确的话,您想更改 variable
method1
指向的内容吗?是这样吗?您可以通过修改局部变量字典中的条目来做到这一点:
您之前的代码没有执行您想要的操作的原因是
func
是对函数method1
的引用>。通过分配给 is,您只需更改它指向的内容即可。您确定要这样做吗?
猴子补丁是令人讨厌的并且会导致许多问题。
If I understand you correctly, you want to change what the variable
method1
points to? Is that right?You can do this by modifying its entry in the dictionary of local variables:
The reason your previous code doesn't do what you want is that
func
is a reference to the functionmethod1
. By assigning to is, you simply change what it points to.Are you sure you want to do this?
Monkeypatching is nasty and can cause many problems.
嗯,简单地修改 method_list 怎么样?
您所描述的更接近于 C++ 引用而不是指针。很少有语言具有这样的语义(少数语言提供了用于传递引用的特殊关键字),包括 Python。
Um, how about simply modifiying method_list?
What you describe is closer to C++ references than to pointers. Few languages have such semantics (a few provide a special keyword for pass-by-reference), including Python.
像这样的东西吗?
不过,我不太确定这样做是否明智。看起来像是与装饰器有关。
Something like this?
I am not so sure this is sensible thing to do, though. Looks like something to do with decorators.