python闭包与装饰器

1、闭包

1.1 通过函数嵌套,函数的返回值是函数对象

def func_closure():
	def get_message(message):
			print('Got a message: {}'.format(message))
	return get_message

send_message = func_closure()
send_message('hello world')

输出:
Got a message: hello word

1.2 内部函数直接可以使用外部函数提供的变量

def line_conf(a, b):
    def line(x):
        return a*x + b
    # 返回闭包结果
    return line

# 传递外部函数参数
line1 = line_conf(1, 1)
line2 = line_conf(4, 5)
# 传入内部函数参数5
print(line1(5))
print(line2(5))

输出:
6
25

2、装饰器

2.1 通过装饰器函数,给原函数进行功能扩展,即已经实现的功能代码不被修改的前提下对其他函数进行功能扩展

def my_decorator(func):
	def wrapper():
		print('wrapper of decorator')
		func()
	return wrapper

# @my_decorator相当于greet = my_decorator(greet)
@my_decorator
def greet():
	print(hello world)

greet()

输出:
wrapper of decorator
hello world

2.2 带有参数的装饰器

1.可以给装饰器函数的内部函数加上相应的参数,但是别的函数就不一定能用此装饰器了
2.可以把*args和**kwargs作为装饰器内部函数的参数,表示可以接受任意数量和类型的参数

def my_decorator(func):
	def wrapper(*args, **kwargs):
		print('wrapper of decorator')
		func(*args, **kwargs)
	return wrapper

2.3 保留原函数

被装饰器装饰过的函数,其元信息会发生变化,可以调用函数名.__name__进行查看元信息,通常可以使用内置装饰器@functools.wraps将原函数的元信息拷贝到对应的装饰器函数里

import functools

def my_decorator(func):
	@functools.wraps(func)
	def wrapper(*args, **kwargs):
		print('wrapper of decorator')
		func(*args, **kwargs)
	return wrapper

@my_decorator
def greet(message):
	print(message)

greet.__name__

输出:
'greet'

2.4 多个装饰器

@decorator1
@decorator2
@decorator3
def cunc():
	...

其等效于@decorator1(@decorator2(@decorator3(func))),由里向外执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值