装饰器如何装饰一个函数?今天番茄加速就来讲一下。
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