一直想详细系统的总结一下decorator装饰器在python里面的作用。顾名思义,装饰器是用来装试的,好比一个房子,没有软装能不能住,能住,但膈不膈应,十分的膈应。所以没有装饰器,python依然可以玩的转,但是真正要掌握这门语言,装饰器还是要了解滴。
那么装饰器装饰的是什么,怎么装试,我们来看一段代码吧
def counttime(func):
def countdown():
start = time.time()
func()
end = time.time()
print('waste{}'.format(start-end))
return countdown
def method():
print("hello world")
if __name__ == "__main__"
temp = counttime(method)
temp()
这段代码可以计算method函数运行的时间,但是显得相当冗余,就像我们的毛坯房,能住,但是膈应。但是装试后,调用就变得简单了许多。装饰器的作用其实简化后就是表达式 temp = <functionname>(para)加上temp()的调用。除此之外,除了装试func函数表达式,我们也可以装试cls类。是不是很形象,为了给某个方法或类装饰一些额外的功能,我们使用到了装饰器。既然已经了解了装饰器的工作原理,继续深入的讲一下他的其它用法。
def counttime(func):
def countdown():
start = time.time()
func()
end = time.time()
print('waste{}'.format(start-end))
return countdown
@counttime
def method():
print("hello world")
if __name__ == "__main__"
#temp = counttime(method)
#temp()
method()
首先我们得讲一下python中默认的装饰器有哪些,比如staticmethod classmethod 和 property。 这三个装饰器都是给类用的。@property最为直接,直译过来就是性质,有些时候我们定义类的方法更像一个属性,我们加上@property后,调用方法就可以由<functionname>() -> <functionname>,是不是....很...嗯。优雅。classmethod和staticmethod两个装饰器装试后,该方法就不再属于某一特定的实例,而是用于单独使用。比如staticmethod装试后,该方法可以不用实例类,直接调用<classname>.<static/methodname>。而classmethod装试后(一般实现形式是<methodname>(cls, para1, para2)),该方法用于实例类时,改变一些该类的属性,比如person的性别和名字,角色的攻击防御等等。
class classdecorator:
def __init__(self, num, name):
self.num = num
self.name = name
@property
def time_killer(self):
return "this is timekiller"
@staticmethod
def time_static():
return "this is time_static"
@classmethod
def addnum(cls, num, name):
return cls(num, name)
另外还有个装饰器叫做functools。它的作用也很优雅。当我们在查看装试后的方法名称是,系统应为装试的原因,看不到它原本的样子,所以在我们阅读软件代码的时候可能带来一些问题。但是如果使用了wraps(functionname)装饰器,就像卸妆水和白酒,体会一下。
import functools
def advanceDecorator(func):
@functools.wraps(func)
def second(*args, **kwargs):
print("this is in the second function")
func(*args, **kwargs)
print("end")
return func(*args, **kwargs)
return second
那么装饰器是否可以有多个呢,答案是可以的。房子除了硬装还有软装啊。我们可以用之前解释的公式套用,stack1(stack2(hello())),可以看得出来stack1嵌套的sec里面func其实代表的是stack2,而stack2嵌套的sec里面的func其实代表的是hello,所以装饰器放置的不同顺序也会改变执行的结果
def stack1(func):
def sec():
print("stack1")
func()
return sec
def stack2(func):
def sec():
print("stack2")
func()
return sec
@stack1
@stack2
def hello():
print("hello world, and stack finished")
有些装饰器是带参数的,表现形式会有些许不同。可以看到俄罗斯套娃,一套一套。多了一套的目的其实也就是为了实现一个目的,把装饰器里面的参数带到下一层。另外如果greet方法里面有参数怎么办呢,在装试函数dotask里面可以用范式参数(*arg,**kwargs)来表示。
def repeatfunc(num_times):
def repeat(func):
def dotask( *args, **kwargs):
for i in range(num_times):
func()
return dotask
return repeat
@repeatfunc(num_times=4)
def greet():
print("hello anna")
print(greet.instance)
最后咱们看一个实际例子,用装饰器在python里面写一个singleton单例。其实单例在python里面用得还是蛮少的,因为大部分用global就可以很轻易的实现了。
def singleton(cls):
global count
print("this is singleton function decorator")
@functools.wraps(cls)
def wrapper_singleton(*args, **kwargs):
if not wrapper_singleton.instance:
wrapper_singleton.instance = cls(*args, **kwargs)
return wrapper_singleton.instance
wrapper_singleton.instance = None
count+=1
print("count is: ", count)
return wrapper_singleton
@singleton
class theOne:
pass
554



被折叠的 条评论
为什么被折叠?



