,[TOC]
1.何为装饰器?
简单来说,装饰器就是用来包装函数或类的“函数”,它接收一个对象(函数对象或类对象),并且返回一个对象(函数对象或类对象)。
2.装饰器如何使用?
用于包装函数的装饰器
首先给出一段代码,然后我们试着用包装器来包装它;
def squareSum(a, b):
print("input", a, b)
return a**2 + b**2
def squareDiff(a, b):
print("input", a, b)
return a**2 - b**2
print(squareSum(4,2))
print(squareDiff(4,2))
现在我们来尝试将上面的代码进行包装;
code1:无参数代码示例
#定义一个装饰器
def decorator(FUNC): ##接收一个可调用对象FUNC
#用来包装的代码段
def hl_FUNC(a, b):
print("input", a, b)
return FUNC(a, b)
return hl_FUNC #返回一个可调用对象
@decorator #注意这里,非常重要,等价于decorator(squareSum)
def squareSum(a, b):
return a**2 + b**2
@decorator
def squareDiff(a, b):
return a**2 - b**2
print(squareSum(4,2))
print(squareDiff(4,2))
code2:有参数代码示例
#新的装饰器包装层
def preString(pre = ''): #新的装饰器的名称,并且有一个参数pre
#旧的装饰器
def decorator(FUNC):
def hl_FUNC(a, b):
print(pre + "input", a, b)
return FUNC(a, b)
return hl_FUNC
return decorator #返回旧的装饰器的名称
@preString('sum +') #注意跟无参的区别
def squareSum(a, b):
return a**2 + b**2
@preString('diff -')
def squareDiff(a, b):
return a**2 - b**2
print(squareSum(4,2))
print(squareDiff(4,2))
其实很简单,就是在旧的装饰器外面又包装了一层,并返回旧的装饰器;
用于包装类的装饰器
接收一个类对象,并且返回一个类对象;
def decorator(class_name):
class class_hl:
def __init__(self, footNum):
self.displayNum = 0
self.type = class_name(footNum) #传入一个footNum参数
def display(self):
self.displayNum += 1;
print("the times of display is: ", self.displayNum)
self.type.display()
return class_hl
@decorator #注意,同样要带上这句,不能忘
class Animal:
def __init__(self, footNum):
self.footNum = footNum
def display(self):
print("the number of foot is: ", self.footNum)
cat = Animal(4) #声明一个要传入装饰器的类对象,并初始化footNum
for i in range(5):
cat.display()
打印结果:
the times of display is: 1
the number of foot is: 4
the times of display is: 2
the number of foot is: 4
the times of display is: 3
the number of foot is: 4
the times of display is: 4
the number of foot is: 4
the times of display is: 5
the number of foot is: 4