Python学习笔记(七)-- 装饰器

,[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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值