fishj 发表于 2018-8-22 22:05:34

helop 关于闭包的问题

在20讲的时候,小甲鱼提到的一个例子
>>> def fun1():
        x = 5
        def fun2():
                x *= x
                return x
        return fun2

>>> fun1()
<function fun1.<locals>.fun2 at 0x023D5810>




>>> def fun1():
        x = 5
        def fun2():
                x *= x
                return x
        return fun2()

>>> fun1()
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
    fun1()
File "<pyshell#33>", line 6, in fun1
    return fun2()
File "<pyshell#33>", line 4, in fun2
    x *= x
UnboundLocalError: local variable 'x' referenced before assignment


这是一个例子,然后他自己敲错了,这个的例子的差别就在renturn fun2()上面,一个右括号,一个没有括号,返回的是截然不同的两种状态,所以我们想问一下,加不加后面的那个括号,有什么样的影响,那个括号代表着什么,那个括号有什么意义

求帮助!!!

凌九霄 发表于 2018-8-23 00:49:53

加了括号,返回的是函数执行完毕的结果,不加括号,返回的是函数的内存地址。简单说就是函数加括号会被执行。

HISIOISIH 发表于 2018-8-27 17:30:53

用大佬的话说 不加()是叫你名字加()是叫你名字去干活。 不加返回的是地址   加返回运行结果
页: [1]
查看完整版本: helop 关于闭包的问题