|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
内嵌函数和闭包
global关键字
>>> count = 5
>>> def Myfun():
count = 10
print(10)
>>> Myfun()
10
>>> print(count)
5
>>>
>>> def Myfun():
global count #用Global修改全局变量
count = 10
print(10)
>>> Myfun()
10
>>> print(count)
10
内嵌函数
>>> def fun1():
print('fun1()正在被调用...')
def fun2():
print('fun2()正在被调用...')
fun2()
>>> fun1()
fun1()正在被调用...
fun2()正在被调用...
>>> fun2()
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
fun2()
NameError: name 'fun2' is not defined
>>>
闭包
函数式编程
>>> def FunX(x):
def FunY(y):
return x * y
return FunY
>>> i = FunX(8)
>>> i
<function FunX.<locals>.FunY at 0x000000000315B9D8>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> FunX(8)(5)
40
>>> FunY(5)
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
FunY(5)
NameError: name 'FunY' is not defined
>>>
>>> def Fun1():
x = 5
def Fun2():
x *= x
return x
return Fun2()
>>> Fun1()
Traceback (most recent call last):
File "<pyshell#60>", line 1, in <module>
Fun1()
File "<pyshell#58>", line 6, in Fun1
return Fun2()
File "<pyshell#58>", line 4, in Fun2
x *= x
UnboundLocalError: local variable 'x' referenced before assignment
>>> def Fun1():
x = [5]
def Fun2():
x[0] *= x[0]
return x[0]
return Fun2()
>>> Fun1()
25
>>>
>>> def Fun1():
x = 5
def Fun2():
nonlocal x #用nonlocal声明x不是全局变量
x *= x
return x
return Fun2()
>>> Fun1()
25
>>>
|
|