【问题标题】:Python: How can I change a function's argument value from an inner frame?Python:如何从内部框架更改函数的参数值?
【发布时间】:2020-01-23 14:10:58
【问题描述】:

在下面的例子中,force 应该改变double 函数的参数x 的值。 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)

【问题讨论】:

  • 你为什么不把“演员”的结果再次分配x

标签: python-3.x parameters arguments frame inspect


【解决方案1】:

This solution works for me.

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

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 2015-04-28
    • 2019-08-11
    • 2021-03-12
    • 2015-11-27
    • 2021-01-14
    • 2021-08-15
    • 1970-01-01
    相关资源
    最近更新 更多