gpt4 book ai didi

python - 如何使用 exec() 将值传递给 python 函数中的变量?

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

一个简单的问题:

exec("a=3")
print(a)

# This will print 3

如果我使用这个:

def func():
exec("a=3")
print(a)

func()

# NameError: name 'a' is not defined.

发生了什么?我如何使用 exec() 在函数中为其赋值?

编辑:我找到了a question有同样的问题,但仍然没有解决。

why do you want to do that?

我知道使用 exec() 不好而且不安全。但最近我试图解决一个 OP 的问题。我遇到了。

最佳答案

Python 知道几种作用域:module global, function local, nonlocal closures, class body .值得注意的是,范围解析定义为 statically at byte code compile time – 最重要的是,名称是指本地/非本地还是全局范围都不能更改。

在这些作用域中,只有全局作用域可以保证与 dict 的行为相似,并且是可写的。局部/非局部作用域一般是不可写的,不能向其中添加新变量。

exec 如果没有传入 locals 将写入全局范围; globals 然后必须显式设置为其默认值 globals()

def func():
exec("a='exec'", globals()) # access only global scope
print(a)

a = 'global'
func() # prints exec

但是,一旦名称是函数的局部名称,exec 就无法修改它。

def func():
a = 'local' # assignment makes name local
exec("a='exec global'", globals())
exec("a='exec locals'", globals(), locals())
print(a)

a = 'global'
func() # prints local

虽然存在类似于dict 的本地/非本地范围表示,但解释器不需要接受对其的更改。

locals()

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Note that at the module level, locals() and globals() are the same dictionary.

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

尽管 exec 确实将局部变量作为 dict,但它们不会像函数局部变量/非局部变量一样对待。未定义修改默认局部变量(locals() 的结果)的尝试。

exec()

... If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. ...

关于python - 如何使用 exec() 将值传递给 python 函数中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60929677/

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