装饰器如何装饰一个函数

装饰器如何装饰一个函数?今天番茄加速就来讲一下。在这里插入图片描述

printStar函数接收一个函数f,返回值也是一个函数,所以满足装饰器的结构要求,所以printStar是一个装饰器。

def printStar(f):

def g():

print(’*’*20)

f()

print(’*’*20)

return g

printStar装饰器实现f函数执行前、后各打印20个*字符。

使用printStar:

@printStar

def f():

print(‘hello world’)

调用:

if name == ‘main’:

### 改变函数功能

f()

打印结果:

********************

hello world

********************

可以很方便的装饰要想装饰的其他函数,如下:

@printStar

def g():

print(‘welcome to Python’)

装饰一个类

除了可以装饰函数f外,还可以装饰类cls,两者原理都是一样的。

下面给出一个装饰器实现单例模式的例子,所谓单例就是类只有唯一实例,不能有第二个。

def singleton(cls):

instance = {}

def get_instance(*args, **kwargs):

if cls not in instance:

instance[cls] = cls(*args, **kwargs)

return instance[cls]

return get_instance

定义字典instance,键值对分别为类和实例,这样确保只cls()一次。

使用装饰器singleton修饰类:

@singleton

class CorePoint:

pass

测试:

if name == ‘main’:

### 改变类的功能

c1 = CorePoint()

c2 = CorePoint()

print(c1 is c2) # True

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值