【发布时间】:2012-01-09 20:36:50
【问题描述】:
“Python 装饰器”和“装饰器模式”有什么区别?
什么时候应该使用 Python 装饰器,什么时候应该使用装饰器模式?
我正在寻找 Python 装饰器的示例以及实现相同功能的装饰器模式。
@AcceptedAnswer
我知道Jakob Bowyer's answer 是有效的。然而,是 Srikar 的回答让我明白了原因。
在 Srikar 的回答和研究给定的资源之后,我编写了这个示例,以便我可以可视化和理解 Python 装饰器和装饰器模式。
我必须不同意 Srikar 的“Python 装饰器不是装饰器模式的实现”。根据我的了解,我坚信 Python 装饰器是装饰器模式的一种实现。只是不是以经典方式。
另外,我需要补充一点,尽管 Srikar 说过“Python 装饰器在定义时为函数和方法添加功能”,你可以在运行时轻松使用 Python 装饰器。
不过,我仍然将 Srikar 的回答标记为已接受,因为它帮助我理解了the implementationPython 中的装饰器模式。
"""
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
【问题讨论】:
-
@Srikar 是正确的。 Here 是另一个你可能会觉得有趣的 SO 问题!
-
@Srikar,我不能接受不能解决问题中描述的问题的回答,抱歉,我的问题中提出的大多数解决方案都不起作用。
-
FWIW,根据Python decorators 上的维基百科文章:“尽管有名称,Python 装饰器并不是装饰器模式的实现”。它继续解释原因。
-
感谢@apcelent。这可能有助于任何人了解这个主题;)
-
Srikar 的回答是绝对正确的。装饰器不适用于运行时修改。我的回答增加了一点细微差别,但他的回答他的回答是最好的。 codementor.io/@sheena/…
标签: python design-patterns decorator