“Python decorators”和“decorator模式”有什么区别?
什么时候应该使用Python decorators,什么时候应该使用decorator模式?
我正在寻找Python decorators和decorator模式的示例。
@AcceptedAnswer
我知道Jakob Bowyer's answer是有效的。但正是斯里卡尔的回答让我明白了原因。
在Srikar给出答案并研究了给定的资源之后,我编写了这个示例,以便能够可视化并理解Python装饰器和装饰器模式。
我必须不同意Srikar的“Python decorator s不是decorator模式的实现”。据我所知,我坚信Python decorators是decorator模式的一个实现。只是不是以经典的方式。
此外,我还需要补充一点,尽管Srikar说“Python decorators在定义时为函数和方法添加功能,您可以在运行时轻松使用Python decorators”。
然而,我仍然将Srikar的答案标记为已接受,因为它帮助我理解Python中装饰器模式的the implementation。"""
Testing Python decorators against the decorator pattern
"""
def function(string):
return string
def decorator(wrapped):
def wrap(string):
# Assume that this is something useful
return wrapped(string.upper())
return wrap
def method_decorator(wrapped):
def wrap(instance, string):
# Assume that this is something useful
return wrapped(instance, string.upper())
return wrap
@decorator
def decorated_function(string):
print('! '.join(string.split(' ')))
class Class(object):
def __init__(self):
pass
def something_useful(self, string):
return string
class Decorator(object):
def __init__(self, wrapped):
self.wrapped = wrapped
def something_useful(self, string):
string = '! '.join(string.split(' '))
return self.wrapped().something_useful(string)
@method_decorator
def decorated_and_useful(self,string):
return self.something_useful(string)
if __name__ == '__main__':
string = 'Lorem ipsum dolor sit amet.'
print(function(string)) # Plain function
print(decorator(function)(string)) # Python decorator at run time
print(decorated_function(string)) # Python decorator at definition time
a = Class()
print(a.something_useful(string)) # Plain method
b = Decorator(Class)
print(b.something_useful(string)) # Decorator pattern
print(b.decorated_and_useful(string)) # Python decorator decorated the decorator pattern