python-3.x - Python:如何从内部框架更改函数的参数值?
问题描述
在下面的例子中,force
应该改变函数的参数x
值double
。ValidateAndCast
检查给定的参数并将其强制转换。所以在这种情况下,在force
返回之后,x
应该是2
,因此 的返回值double
应该是 4。假设所有的改变都是在force
函数中完成的。
我如何实现这一目标?inspect
到目前为止,我已经研究并将继续学习。
def is_number(x):
try:
float(x)
return True
except:
return False
def to_int(x):
return int(float(x))
def double(x):
force(x=ValidateAndCast(is_number, to_int))
return x * 2
x = '2.54'
y = double(x)
print(y)
解决方案
import ctypes
import inspect
def change():
def apply(frame):
frame.f_locals['x'] = 4
ctypes.pythonapi.PyFrame_LocalsToFast(ctypes.py_object(frame), ctypes.c_int(1))
calling_frame = inspect.stack()[1][0]
apply(calling_frame)
def f(x):
change()
return x * 2
y = f(2)
print(y) # prints 8
推荐阅读
- amazon-rds - 调用 DescribeDBInstances 操作时:无法识别的过滤器名称:tag:Name
- javascript - 使用 vue cli 或 webpack 构建单个 vue 组件
- amazon-ecs - ECS 滚动更新可能导致 502 Bad Gateway
- ios - 如何启用多点触控并同时绘制两条线?
- qt - C++: Qt:libraries:screenGeometry()
- ios - 应该如何配置专门的方案来在基于 iOS 的设备上执行逻辑单元测试
- oracle - 如何处理直接路径插入中的行错误
- javascript - Javascript数组过滤子!
- vbscript - 如何根据行号删除文本文件的特定行?
- wamp - WAMP - 如何启用“http://”前缀