python第11天 函数之其他参数

个人笔记!!!

  1. 收集参数
>>> def my(*args):
	print("有{}个参数".format(len(args)))
	print("第2个参数是,{}".format(args[1]))

	
>>> my(1,2,3,4,5)5个参数
第2个参数是,2

#2
>>> def my():
	return 1,2,3

>>> my()
(1, 2, 3)
>>> a,s,d = my()
>>> a
1
>>> s
2
>>> d
3

#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
#4
>>> 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

#2
>>> 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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值