python装饰器

函数可以作为参数

  • 函数本身在python里面是一个对象, 也可以作为参数被传入另一个参数里.
def double(x):
	return x*2

def triple(x):
	return x*3

def calc_number(func,x):
	print(func(x))
	
calc_number(double,3)
calc_number(triple,3)

函数可以作为返回值

def get_multiple_func(n):
	def multiple(x):
		return n*x
	return multiple
	
double = get_multiple_func(2)
triple = get_multiple_func(3)

print(double(2), triple(3))

装饰器

方法装饰器
  • 输入是函数, 输出大部分也是函数.
  • 一个极简的装饰器例子:
def dec(f):
	pass

@dec
def double(x):
	return x*2
	
# 完全等价
double = dec(double)
类装饰器
posted @ 2023-07-26 08:56  sdulyq  阅读(11)  评论(0)    收藏  举报