gpt4 book ai didi

python - 如何在嵌套类中模拟实例变量

转载 作者:太空宇宙 更新时间:2023-11-03 18:01:57 25 4
gpt4 key购买 nike

简化示例:

def bind_method(**config):
class InstagramAPIMethod(object):
def __init__(self, *args, **kwargs):
self.return_json = kwargs.pop("return_json", False)
def _call(*args, **kwargs):
method = InstagramAPIMethod(*args, **kwargs)
return method.__dict__

return _call

class InstAPI():
result = bind_method(foo='bar')

api = InstAPI()
print api.result()

# {'return_json': False}

从上面的示例中,是否有任何方法可以“猴子修补”“InstAPI”实例或使用“部分”函数将值硬编码为“_call”函数,以便它返回 {' return_json': True} ?

现实生活示例:

https://github.com/Instagram/python-instagram.git

如果你看https://github.com/Instagram/python-instagram/blob/master/instagram/bind.py#L42-L69

您将看到 bind_method 函数,如下所示:

def bind_method(**config):
class InstagramAPIMethod(object):
path = config['path']
method = config.get('method', 'GET')

https://github.com/Instagram/python-instagram/blob/master/instagram/bind.py#L64行有一个参数。我找不到如何将其更改为 True 的明确方法。

最佳答案

mock给你一些方法来做到这一点。这个案子有点棘手,因为

  1. InstagramAPIMethodbind_method 函数中定义
  2. InstAPI 在加载时存储 bind_method 定义

因此修补 bind_methodInstagramAPIMethod 类没有效果。您只有一个机会:修补 InstAPI.result。我考虑了两种情况:

  1. 我不关心 bind_method 中的工作,我只需要 api.result() 返回一个像 {'return_json': True 的字典}
  2. 我希望 result() 返回的正是 bind_method 返回的内容,除了更改某些值

遵循玩具示例的代码,该代码也应该适用于现实生活。

def bind_method(**config):
class InstagramAPIMethod(object):
def __init__(self, *args, **kwargs):
self.return_json = kwargs.pop("return_json", False)
def _call(*args, **kwargs):
method = InstagramAPIMethod(*args, **kwargs)
return method.__dict__
return _call

class InstAPI():
result = bind_method(foo='bar')

api = InstAPI()
print api.result()


from mock import patch
#Patch directly InstAPI.result
with patch("__main__.InstAPI.result",return_value={'return_json': True}):
api = InstAPI()
print api.result()

#The wrapper of bind_method
def new_instapi_result(**kwargs):
def functor(**config):
d = bind_method(**config)()
d.update(kwargs)
return d
return functor

#Patch and wrap bind_method
with patch("__main__.InstAPI.result",side_effect=new_instapi_result(return_json = True)):
api = InstAPI()
print api.result()

关于python - 如何在嵌套类中模拟实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27556181/

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