definc():c =0definner():c +=1return creturn innerf = inc()print(1, f())print(2, f())# 报错原因,inner中c += 操作是inner函数中的c,因为没有定义inner中的c变量,所以不能用。# 报错内容:UnboundLocalError: cannot access local variable 'c' where it is not associated with a value
definc():c =0# 自由变量,局部变量definner():global cc +=1return creturn innerf = inc()print(1, f())print(2, f())# 报错原因:inner定义了global c,但是python全局中没有c变量# 报错内容:NameError: name 'c' is not defined
definc():global cc =0# 自由变量,局部变量definner():global cc +=1return creturn innerf = inc()print(1, f())print(2, f())# inc中和inner中都必须定义global才能使用# 返回结果:1 1# 返回结果:2 2
defa():nonlocal cc =100print(a())# 报错原因:nonlocal c不是本函数的c,只能向上一层函数找,但是在上一层就是global了,nonlocal不允许在global中使用。# 报错内容:SyntaxError: no binding for nonlocal 'c' found
definc():a =1000 c =0definner():nonlocal cc +=1return creturn innerf = inc()print(1, f())print(2, f())# 此代码主要说明,a没有闭包,因为在嵌套函数inner中没有使用到a
definc():a =1000 c =0definner():nonlocal cc +=1return cdeft():nonlocal aprint(a)print(t.__closure__)return innerreturn tf = inc()print(1, f())print(2, f())# 此代码中,a和c都用到了闭包,因为函数inner用了c,函数t用了a
c =0defa():c =1defb():c =2defc():c =3print(c)# 闭包遵循就近原则,此代码为例,如函数c的c变量注释掉,打印的c就是函数中的c,以此类推。
Python之禅
在Python的解释器中隐藏一个彩蛋,输入import this就会返回19条Python之禅,具体如下:
import this
The Zen of Python, by Tim Peters Python之禅 ,by Tim Peters
Beautiful is better than ugly.
优美好于丑陋&…
看下open clip论文 Learning Transferable Visual Models From Natural Language Supervision These results suggest that the aggregate supervision accessible to modern pre-training methods within web-scale collections of text surpasses that of high-quality crowd…