108. python高级------闭包与装饰器(3)

108. python高级------闭包与装饰器(3)

python修炼第二十四天

2019年 4月 23日 晴

内容回顾

1.函数定义

def test():
	print("test")
print(test) # 函数的引用,得到的是函数体在内存的地址
test()      # 函数的调用

函数的引用,得到的是函数体在内存的地址

def test():
	print("haha")
	return 1


# 打印test函数在内存的地址
print(test)

test()

# 打印字符串test
print(test())

结果:
<function test at 0x000001BA94FE3E18>
haha
haha
1
打印调用的函数时, 会先执行函数并且打印函数返回值,如果函数没有返回值,则返回None

2.函数定义进阶

def test(*args, **kwargs):
	print("test", args)
	print("test", kwargs)


def test2(func, *args, **kwargs):
	print(func)
	print("test2:", args)
	print("test2", kwargs)
	func(*args, **kwargs)  # 调用,类似拆包


test2(test, 123, a=123)

执行结果:
<function test at 0x000001B30E493E18>
test2: (123,)
test2 {'a': 123}
test (123,)
test {'a': 123}

说明:
该程序运行时,先定义test函数,test2函数,再运行第13行,第13行中参数test,是test函数的引用,即传参数时,传递的是test函数体的地址,运行至第6行,func参数是test函数体的地址,*args123,**kwargsa=123; 运行至第7,8,9行,打印test的引用(地址),args:(123,),kwargs: {"a": 123};运行至第10行, func(*args, **kwargs)相当于是test(*args,**kwargs) ,与此同时还进行了元组字典容器转化成普通类型(在上一节回提到为什么不能用 test( args, kwargs),此时的func(*args,**kwargs)相当于func(123,a =123)传递参数给func1,打印结果

猜你喜欢

转载自blog.csdn.net/qq_40455733/article/details/89639885