个人笔记!!!
- 收集参数
>>> def my(*args):
print("有{}个参数".format(len(args)))
print("第2个参数是,{}".format(args[1]))
>>> my(1,2,3,4,5)
有5个参数
第2个参数是,2
>>> def my():
return 1,2,3
>>> my()
(1, 2, 3)
>>> a,s,d = my()
>>> a
1
>>> s
2
>>> d
3
>>> def myfunc(*a,b,c):
print(a,b,c)
>>> myfunc(1,2,3,4,5,b=44,c=224)
(1, 2, 3, 4, 5) 44 224
>>> def abc(a,*,b,c):
print(a,b,c)
>>> abc(1,b=44,c=43)
1 44 43
>>> def myfunc(a,*b,**c):
print(a,b,c)
>>> myfunc(1,2,3,x=3,c=3,g=44)
1 (2, 3) {'x': 3, 'c': 3, 'g': 44}
2.解包参数
>>> args = (1,2,3,4,5)
>>> def my(a,b,c,d,e):
print(a,b,c,d,e)
>>> my(*args)
1 2 3 4 5
>>> a
1
3.作用域之局部作用域
>>> def mufunc():
s = 1111
print(s)
>>> mufunc()
1111
4.全局作用域
>>> a = 333
>>> def myfunc():
print(a)
>>> myfunc()
333
5.global语句
>>> x = 2222
>>> def myfunc():
global x
x = 3333
print(x)
>>> myfunc()
3333
>>> print(x)
3333
6.嵌套函数
>>> def funA():
x = 1314
def funB():
x = 888
print("In funb,x=",x)
funB()
print("In funa,x=",x)
>>> funA()
In funb,x= 888
In funa,x= 1314
7.nonlocal语句
>>> def funA():
x = 1314
def funB():
nonlocal x
x = 888
print("In funb,x=",x)
funB()
print("In funa,x=",x)
>>> funA()
In funb,x= 888
In funa,x= 888
8.闭包,俗称工厂函数
>>> def power(exp):
def exp_of(base):
return base ** exp
return exp_of
>>> a = power(2)
>>> s = power(3)
>>> a(2)
4
>>> s(2)
8
>>> def outer():
a = 0
s = 0
def inner(a1,s1):
nonlocal a,s
a += a1
s += s1
print(f"现在,a = {a},s = {s}")
return inner
>>> move = outer()
>>> move(1,2)
现在,a = 1,s = 2
>>> move(-2,3)
现在,a = -1,s = 5
>>> def func():
a = 1
print("This is func")
def func1(nub):
print("This is func1")
print(nub + 1)
return func1
>>> v = func()
This is func
>>> v(2)
This is func1
3
>>> print("闭包例子2")
闭包例子2
>>> mylist = [1,2,3,4,5]
>>> def func(obj):
print("func:",obj)
def func1():
obj[0] += 1
print("func1:",obj)
return func1
>>> q = func(mylist)
func: [1, 2, 3, 4, 5]
|