Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

python - Binding an objects value within a function (closure)

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a keyword argument:

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

x = 7
f()  # 3

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.).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...