Python装饰器2-__call__方法与类装饰器

简介: __call__方法、创建类装饰器、装饰器的应用场景

一、__call__方法

上一篇《Python装饰器-闭包与函数装饰器》中主要介绍了装饰器的基本原理以及如何创建函数装饰器,而本篇的主要内容是如何创建一个类,并使其作为装饰器使用。在学习类装饰器前,需要先了解python中的__call__方法。__call__方法是python魔法方法的一种,它的作用是将类的实例化对象变成可调用对象,类似于像函数一样被调用。默认情况下:__call__方法在函数中是实现的,而在类中是没有被实现的。

1.函数与__call__方法

callable( )方法

通过callable( ) 方法可以判断对象是否为可调用对象:

输出结果为True,因此函数introduce是一个可调用对象。

function(args)的等价写法

function(*args)等价于function.__call__(*args)

2.类与__call__方法

callable( )方法

默认情况下,在类中是没有实现__call__方法的,此时通过callable( )方法,传入实例对象,运行结果为FALSE,表示这个实例对象不是一个可调用对象。直接调用实例对象,会报错提示“TypeError: 'xxxx' object is not callable”

在类中定义__call__方法

classIntroduce(object):
def__init__(self, name, city):
self.name=nameself.city=citydefintroduce(self):
print(f"我叫{self.name}, 我来自{self.city}")
def__call__(self, age):
print(f"我今年{age}岁了")
intro=Introduce("刘德华", '香港')
print(callable(intro))
intro(28)
intro.__call__(28)

在Introduce类中定义了__call__方法后,此时:

  • 再通过callable()方法调用实例对象intro,运行结果就是True了,表示intro是一个可调用对象;
  • intro(28)实际是调用__call__方法,执行__call__方法中的逻辑;
  • intro(28)等价于intro.__call__(28)

二、类装饰器

相比函数类装饰器,类装饰器具有灵活度大、高内聚、封装性等优点。

1.类装饰器

在明白了__call__方法的作用及原理后,类装饰器就变得简单易懂了。例如我想要定义一个类装饰器,用来统计函数的运行耗时:

importtimeclassTimer(object):
def__init__(self, obj):
self.obj=objdef__call__(self, *args, **kwargs):
start_time=time.time()
self.obj(*args, **kwargs)
end_time=time.time()
use_time=end_time-start_timeprint("函数%s运行耗时:%s秒"% (self.obj.__name__, use_time))
@Timerdefinfo():
time.sleep(2)
print("life is short, i need python")
info()

运行结果如下:

2.带参数的类装饰器

同样是统计函数运行耗时的例子,假如此时我想在函数运行时灵活地输出一些自定义的信息,而不是固定写死的信息,那么,此时就可以给类装饰器定义一个初始化变量,用于存储想要灵活输出的信息:

classTimer2(object):
def__init__(self, prefix):
self.prefix=prefixdef__call__(self, func):
defwrapper(*args, **kwargs):
start_time=time.time()
ret=func(*args, **kwargs)
end_time=time.time()
use_time=end_time-start_timeprint("%s, 函数运行共耗时: %s秒"% (self.prefix, use_time))
returnretreturnwrapper

例如,我想要在函数运行时输出当前时间:

@Timer2(prefix=f"当前时间{time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())}")
definfo():
time.sleep(2)
print("life is short, i need python")

此时就相当于把prefix的内容和__call__函数原本定义的内容实现了灵活拼接,运行结果如下:

三、装饰器应用场景

函数装饰器与类装饰器之间是可以相互修饰的,也就是说函数装饰器既可以修饰函数、也可以修饰类,类装饰器既可以修饰类、也可以修饰函数。

1.函数装饰器装饰函数

给被装饰对象增加类似于setUp和tearDown的前后置功能

defwrapper_info(func):
definner(*args, **kwargs):
print("开始介绍...")
res=func(*args, **kwargs)
print("介绍结束...")
returnresreturninner@wrapper_infodefintroduce3(name, age, city):
print(f"我叫{name}, 我今年{age}岁了, 我来自{city}")
introduce3('刘德华', 28, '香港')
'''开始介绍...我叫刘德华, 我今年28岁了, 我来自香港介绍结束...'''

2.函数装饰器装饰类

给被装饰对象增加属性

defwrapper(obj):
obj.phone_number=15252188888returnobj@wrapperclassIntroduce:
def__init__(self, name, city):
self.name=nameself.city=citydefintroduce(self):
print(f"我叫{self.name}, 我来自{self.city}")
intro=Introduce("刘德华", '香港')
intro.introduce()
print(intro.phone_number)  # 给Introduce类增加了一个phone_number的属性'''我叫刘德华, 我来自香港15252188888'''

3.类装饰器装饰函数

统计函数运行时间

classTimer2(object):
def__init__(self, prefix=''):
self.prefix=prefixdef__call__(self, func):
defwrapper(*args, **kwargs):
start_time=time.time()
ret=func(*args, **kwargs)
end_time=time.time()
use_time=end_time-start_timeprint("%s, 函数运行共耗时: %s秒"% (self.prefix, use_time))
returnretreturnwrapper@Timer2(prefix="测试类装饰器")
definfo():
time.sleep(2)
print("life is short, i need python")
info()
'''life is short, i need python测试类装饰器, 函数运行共耗时: 2.0003740787506104秒'''

4.类装饰器装饰类

这里仅仅为了证明和演示类装饰器可以用来装饰类,实际意义并不大。

classDecorator:
def__init__(self, obj):
self.obj=objdef__call__(self, *args, **kwargs):
res=self.obj(*args, **kwargs)
print("测试类装饰器用来装饰类")
returnres# 类装饰器装饰类@DecoratorclassAnimals:
defdogs(self):
print('wong wong')
ani=Animals()
ani.dogs()
'''测试类装饰器用来装饰类wong wong'''

5.函数装饰器装饰类中的方法

同样以统计函数运行时间为例,定义装饰器和引用装饰器都是一样的。

defwrapper(func):
definner(*args, **kwargs):
start_time=time.time()
res=func(*args, **kwargs)
end_time=time.time()
use_time=end_time-start_timeprint("函数运行共耗时: %s秒"% (use_time))
returnresreturninnerclassGoods(object):
def__init__(self, goods, weight, price):
self.goods=goodsself.weight=weightself.price=price@wrapperdefbuying(self):
time.sleep(1)
print(f"商品: {self.goods}, 重量: {self.weight}, 价格: {self.price}")
goods=Goods("西瓜", "10KG", "30元")
goods.buying()
'''商品: 西瓜, 重量: 10KG, 价格: 30元函数运行共耗时: 1.0001726150512695秒'''


相关文章
|
18天前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
130 1
|
2月前
|
机器学习/深度学习 数据采集 数据挖掘
基于 GARCH -LSTM 模型的混合方法进行时间序列预测研究(Python代码实现)
基于 GARCH -LSTM 模型的混合方法进行时间序列预测研究(Python代码实现)
|
11天前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
213 101
|
18天前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
165 99
|
18天前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
146 98
|
23天前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
1月前
|
存储 缓存 测试技术
理解Python装饰器:简化代码的强大工具
理解Python装饰器:简化代码的强大工具
|
10天前
|
人工智能 数据安全/隐私保护 异构计算
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
143 8
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
|
11天前
|
缓存 测试技术 Python
解锁Python超能力:深入理解装饰器
解锁Python超能力:深入理解装饰器
67 2

推荐镜像

更多