函数 - 关于python闭包的一些疑问
PHPz
PHPz 2017-04-17 17:29:24
0
4
233
def count():
    fs = []
    for i in range(1, 4):
        def f(j):
            def g():
                return j*j
            return g    
        r = f(i)    
        fs.append(r)    #fs作为列表,为什么可以append(r)?(而r是f所返回的函数)
    return fs           #个人的想法应该是fs.append(r())

f1, f2, f3 = count()
print f1(), f2(), f3()

想弄明白的是:这里传入append的r是以什么形式传入的呢
谢谢各位指教:D

PHPz
PHPz

学习是最好的投资!

reply all(4)
迷茫

is passed in in the form of a function definition, similar to delayed calling, which is not obvious in your example,

def count():
    def r():
        return "hello world"
    return r          
x =  count()  
print x #<function r at 0x7fc562978668>
print x() # hello world

You can think of r in return r in the function as a variable, but this variable saves the definition of the function.
The actual call to the function is through x() later

左手右手慢动作

r is an object, and the type of this object is a function.

In other words, r is an object of type function, like

  • 1 is an object of type integer

  • 'hi' is the same as an object of type string

大家讲道理

If you change it to fs.append(r()), it is also possible, but the meaning of the function is different. After executing the count() function, it will return the result [1, 4, 9], and you can no longer use print f1(), f2(), f3() to print out the results because: fs.append(r())也是可以的,但是函数意义就不同了,执行count()函数后其会返回结果[1, 4, 9],而不能再使用print f1(), f2(), f3()打印出结果,原因在于:

r=f(i)=g

注意这里是 g 不是 g(),所以执行count()返回的其实是[g1, g2, g3]一个包含三个闭包函数的列表,每个闭包函数绑定的自由变量不同(分别是1, 2, 3),因此将这个列表解包给f1, f2, f3后,执行print f1(), f2(), f3()相当于执行三个函数后并打印出结果,因此最终输出1, 4, 9 rrreee

Note that this is g not g(), so what is returned by executing count() is actually [g1, g2, g3] A list containing three closure functions. Each closure function binds different free variables (respectively 1, 2, 3), so unpack this list to f1, f2, f3 , executing print f1(), f2(), f3() is equivalent to executing three functions and printing out the results, so the final output is 1, 4, 9🎜
大家讲道理

f1 = fs[0] = r = gf1 = fs[0] = r = g

所以才能

f1()

That’s why 🎜 🎜f1()🎜
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template