gpt4 book ai didi

Python 两个函数的变量作用域

转载 作者:行者123 更新时间:2023-12-01 02:00:56 24 4
gpt4 key购买 nike

我尝试搜索一下这个问题,但找不到实际的答案。我正在尝试实现一个函数(magic_debug),以便在另一个函数(somefunc)中调用时,它可以访问变量在 somefunc 中并按如下方式打印出来:

def magic_debug(s, *args, **kwargs):
s2 = s.format(x=x,y=y,z=args[0])
print(s2)


def somefunc():
x = 123
y = ['a', 'b']
magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y))

somefunc()

预期输出 --> x 的值为 123,列表为 len 2 的 ['a', 'b']

最佳答案

这确实是一个常见问题,请尝试使用inspect

def magic_debug(s, *args, **kwargs):
import inspect
parent_local_scope = inspect.currentframe().f_back.f_locals
s2 = s.format(**parent_local_scope, z=args[0])
print(s2)


def somefunc():
x = 123
y = ['a', 'b']
magic_debug('The value of x is {x}, and the list is {y} of len {z}', len(y))

somefunc()

输出:

The value of x is 123, and the list is ['a', 'b'] of len 2

关于Python 两个函数的变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49641454/

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