我怎样才能通过我的本地人,并直接从另一个函数访问变量? [英] How can I pass my locals and access the variables directly from another function?
问题描述
Let's say I have this :
def a(dict):
locals().update(dict)
print size
def b():
size = 20
f(locals())
直接从<$ c $访问大小
变量需要做些什么c> a 函数?我知道:
What do I have to do to access the size
variable directly from the a
function? I know of :
size = dict["size"]
但我认为应该有更直接的方式。我尝试使用 locals()。update(dict)
,但它不起作用。有没有更好的方法?
but I think there should be a more direct way. I tried using locals().update(dict)
but it didn't work. Is there a betteer way ?
推荐答案
Python编译器通过在编译时识别一个函数的名字是否优化了对局部变量的访问访问是本地的(即,在该功能内分配或以其他方式绑定的裸号)。所以如果你编码:
The Python compiler optimizes access to local variables by recognizing at compile time whether the barenames a function is accessing are local (i.e., barenames assigned or otherwise bound within the function). So if you code:
def lv1(d):
locals().update(d)
print zap
编译器知道该裸号 zap
不是本地的(在函数 lv1
中没有赋值),所以它编译代码以全局的方式访问它 - 不管 d
包含无关紧要。
the compiler "knows" that barename zap
is NOT local (not assigned in function lv1
) and so it compiles code to access it as a global instead -- whatever d
contains won't matter.
如果您喜欢缓慢且臃肿的代码,可以使用 exec
- 当编译器看到关键字 exec
时,它知道你正在试图让你的代码尽可能慢,臃肿和错误,所以它没有以任何方式进行合作,只是关于。
If you prefer slow and bloated code, you can defeat the optimization by using an exec
inside the function -- when the compiler sees the keyword exec
, it KNOWS you're trying to make your code as slow, bloated and buggy as possible, and so it cooperates by not optimizing in any way, just about.
所以,下面的代码可以按照你的意愿工作:
So, the following code works as you desire:
def lv1(d):
exec ""
locals().update(d)
print zap
lv1({'zap': 23})
它会发出 23
,如你所愿。
我希望从在不作为的幽默之上,我们不建议使用这种技术,但我最好明确地说明一下:对于编写 print zap
代替<$的可疑语法乐趣c $ c> print locals()['zap'] ,你在性能上付出了沉重的代价。尽管如此,像许多危险的工具,对于真正有经验的古鲁级程序员,在真正知道自己在做什么以及为什么这些原因的情况下,在极少数情况下可能会有用, exec
是在那里,可供您随意使用(或误用):Python不会妨碍您的行为! - )
I hope it's clear from the above "deadpan humor" that the technique is not recommended, but I'd better spell it out very explicitly: for the dubious syntactic pleasure of writing print zap
in lieu of print locals()['zap']
, you ARE paying a hefty price in terms of performance. Still, like all sorts of dangerous tools that can be useful in rare use cases for really experienced guru-level programmers who really truly know what they're doing and why, exec
is there, available for you to use (or mis-use) at your whim: Python does NOT stand in your way!-)
这篇关于我怎样才能通过我的本地人,并直接从另一个函数访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!