[英]Assign variable to local scope of function in Python
I'd like to assign a variable to the scope of a lambda that is called several times. 我想将一个变量分配给多次调用的lambda范围。 Each time with a new instance of the variable.
每次带有变量的新实例。 How do I do that?
我怎么做?
f = lambda x: x + var.x - var.y
# Code needed here to prepare f with a new var
result = f(10)
In this case it's var I'd like to replace for each invocation without making it a second argument. 在这种情况下,它是var我想为每个调用替换而不将其作为第二个参数。
Variables undefined in the scope of a lambda
are resolved from the calling scope at the point where it's called. 在
lambda
范围内未定义的变量在调用点被调用范围解析。
A slightly simpler example... 一个更简单的例子...
>>> y = 1
>>> f = lambda x: x + y
>>> f(1)
2
>>> y = 2
>>> f(1)
3
...so you just need to set var
in the calling scope before calling your lambda
, although this is more commonly used in cases where y
is 'constant'. ...因此,您只需要在调用
lambda
之前在调用范围内设置var
,尽管在y
是'constant'的情况下更常用。
A disassembly of that function reveals... 该功能的反汇编显示...
>>> import dis
>>> dis.dis(f)
1 0 LOAD_FAST 0 (x)
3 LOAD_GLOBAL 0 (y)
6 BINARY_ADD
7 RETURN_VALUE
If you want to bind y
to an object at the point of defining the lambda
(ie creating a closure ), it's common to see this idiom... 如果您想在定义
lambda
将y
绑定到对象(即创建一个Closure ),通常会看到这个惯用法...
>>> y = 1
>>> f = lambda x, y=y: x + y
>>> f(1)
2
>>> y = 2
>>> f(1)
2
...whereby changes to y
after defining the lambda
have no effect. ...因此在定义
lambda
之后更改为y
无效。
A disassembly of that function reveals... 该功能的反汇编显示...
>>> import dis
>>> dis.dis(f)
1 0 LOAD_FAST 0 (x)
3 LOAD_FAST 1 (y)
6 BINARY_ADD
7 RETURN_VALUE
f = functools.partial(lambda var, x: x + var.x - var.y, var)
将为您提供一个参数( x
)的函数( f
),其中var
固定为定义时的值。
You cannot use the assignment statement in lambda expression, so you'll have to use a regular named function: 您不能在lambda表达式中使用赋值语句,因此必须使用常规的命名函数:
def f(x):
global var
var = x
Note the use of the "global" keyword. 注意使用“ global”关键字。 Without it, Python will assume you want to create a new "var" variable in the local scope of the function.
没有它,Python将假定您要在函数的本地范围内创建一个新的“ var”变量。
Make it another parameter: 使其成为另一个参数:
f = lambda x,var: x + var.x - var.y
result = f(10, var)
Lambda or regular function, the only way you can change a variable in the scope of a function is via an argument. Lambda或常规函数,在函数范围内更改变量的唯一方法是通过参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.