在函数中绑定对象值(闭包) [英] Binding an objects value within a function (closure)

查看:179
本文介绍了在函数中绑定对象值(闭包)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SML(我在Python之前学习的函数式编程语言)中,我可以执行以下操作:

In SML (a functional programming language that I learned before Python), I can do the following:

val x = 3;
fun f() = x;
f();
>>> 3
val x = 7;
f();
>>> 3

然而,在Python中,第一个调用将给出3,第二个调用将给予7.

In Python, however, the first call will give 3 and the second one will give 7.

x = 3
def f(): return x
f()
>>> 3
x = 7
f()
>>> 7

如何在Python中将变量的值绑定到函数?

How do I bind the value of a variable to a function in Python?

推荐答案

您可以使用关键字参数:

You can use a keyword argument:

x = 3
def f( x=x ): 
    return x

x = 7
f()  # 3

创建函数时为关键字参数分配 。函数运行时在函数的作用域中查找其他变量。 (如果它们不在函数的作用域中,python在包含函数等的范围内寻找变量)。

Keyword arguments are assigned when the function is created. Other variables are looked up in the function's scope when the function is run. (If they're not found in the function's scope, python looks for the variable in the scope containing the function, etc, etc.).

这篇关于在函数中绑定对象值(闭包)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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