动态设置局部变量 [英] Dynamically set local variable

查看:75
本文介绍了动态设置局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中动态设置局部变量(变量名是动态的)?

How do you dynamically set local variable in Python (where the variable name is dynamic)?

推荐答案

与其他答案相反已经发布,您不能直接修改 locals()并期望它能正常工作。

Contrary to other answers already posted you cannot modify locals() directly and expect it to work.

>>> def foo():
    lcl = locals()
    lcl['xyz'] = 42
    print(xyz)


>>> foo()

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    foo()
  File "<pyshell#5>", line 4, in foo
    print(xyz)
NameError: global name 'xyz' is not defined

修改 locals()未定义。在函数外部,当 locals() globals()相同时,它将起作用。在函数内通常会不起作用。

Modifying locals() is undefined. Outside a function when locals() and globals() are the same it will work; inside a function it will usually not work.

使用字典或在对象上设置属性:

Use a dictionary, or set an attribute on an object:

d = {}
d['xyz'] = 42
print(d['xyz'])

或者,如果您愿意,可以使用以下类:

or if you prefer, use a class:

class C: pass

obj = C()
setattr(obj, 'xyz', 42)
print(obj.xyz)

编辑
访问不是函数的名称空间中的变量(因此,模块,类定义,实例)通常由字典查找完成(正如Sven在注释中指出的那样,有例外,例如定义 __ slots __ 的类)。可以优化函数局部变量的速度,因为编译器通常会事先知道所有名称,因此只有在调用 locals()之前,才会有字典。

Edit: Access to variables in namespaces that aren't functions (so modules, class definitions, instances) are usually done by dictionary lookups (as Sven points out in the comments there are exceptions, for example classes that define __slots__). Function locals can be optimised for speed because the compiler (usually) knows all the names in advance, so there isn't a dictionary until you call locals().

在Python的C实现中, locals()(从函数内部调用)创建一个从当前值初始化的普通字典局部变量在每个函数中,对 locals()的任何数量的调用都将返回相同的字典,但是对 locals()的每次调用将使用局部变量的当前值对其进行更新。这给人的印象是字典元素的赋值被忽略了(我最初是这样写的)。因此,对字典中现有键的修改是从 locals()返回的,因此只能持续到下一次调用 locals()

In the C implementation of Python locals() (called from inside a function) creates an ordinary dictionary initialised from the current values of the local variables. Within each function any number of calls to locals() will return the same dictionary, but every call to locals() will update it with the current values of the local variables. This can give the impression that assignment to elements of the dictionary are ignored (I originally wrote that this was the case). Modifications to existing keys within the dictionary returned from locals() therefore only last until the next call to locals() in the same scope.

在IronPython中,工作原理略有不同。任何在其内部调用 locals()的函数均使用字典作为其局部变量,因此对局部变量的赋值会更改字典,而对字典的赋值会更改变量 BUT ,只有在您以该名称显式调用 locals()时。如果在IronPython中将其他名称绑定到 locals 函数,则调用该函数将为您提供绑定该名称的作用域的局部变量,并且无法访问函数locals通过它:

In IronPython things work a bit differently. Any function that calls locals() inside it uses a dictionary for its local variables so assignments to local variables change the dictionary and assignments to the dictionary change the variables BUT that's only if you explicitly call locals() under that name. If you bind a different name to the locals function in IronPython then calling it gives you the local variables for the scope where the name was bound and there's no way to access the function locals through it:

>>> def foo():
...     abc = 123
...     lcl = zzz()
...     lcl['abc'] = 456
...     deF = 789
...     print(abc)
...     print(zzz())
...     print(lcl)
...
>>> zzz =locals
>>> foo()
123
{'__doc__': None, '__builtins__': <module '__builtin__' (built-in)>, 'zzz': <built-in function locals>, 'foo': <function foo at 0x000000000000002B>, '__name__': '__main__', 'abc': 456}
{'__doc__': None, '__builtins__': <module '__builtin__' (built-in)>, 'zzz': <built-in function locals>, 'foo': <function foo at 0x000000000000002B>, '__name__': '__main__', 'abc': 456}
>>>

这可以随时更改。唯一可以保证的是,您不能依赖于分配给 locals()返回的字典的结果。

This could all change at any time. The only thing guaranteed is that you cannot depend on the results of assigning to the dictionary returned by locals().

这篇关于动态设置局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆