问题描述
" python装饰器"和"装饰器图案"有什么区别?
我什么时候应该使用python装饰器,什么时候应该使用装饰器图案?
我正在寻找python装饰器的示例,而装饰符图案也相同.
@acceptedanswer
我知道 jakob Bowyer的答案有效.然而,这是斯里卡(Srikar)的回答使我明白了为什么.
在Srikar的回答和研究给定资源之后,我写了这个示例,因此我可以可视化和理解Python Decorator和Decorator图案.
i必须与Srikar的" python装饰器"不同意不是装饰图案的实现.在我学到了什么之后,我坚信python装饰器是装饰图案的实现.不是经典的方式.
也,我还需要补充一点,尽管Srikar说" python装饰师在定义时间 ",您可以在运行时间轻松使用python装饰器.
然而,我仍然可以接受Srikar的答案,因为它帮助我了解 实施 python .
""" 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
推荐答案
装饰器模式 - 在面向对象的编程中,装饰器模式是一种设计模式,可以动态地将行为添加到现有对象中.如果在设计时完成了一些基础,则可以使用装饰器图案在运行时延伸(装饰)某个对象的功能,而不是同一类的其他实例.
python中的装饰器 - 尽管名称,python装饰器并不是装饰器图案的实现.装饰器图案是一种设计模式,用于静态键入对象的编程语言,以允许在运行时添加功能. Python装饰器在定义时间为功能和方法添加功能,因此比Decorator-Pattern类是更高的构造.
装饰符图案本身在Python中是可以在python中实现的,因为该语言是鸭子的,因此通常不被认为.因此,在python中,装饰器是用于修改函数,方法或类定义的任何可调用的python对象.
我希望我能有所作为.以防万一您不完全理解,请浏览这些链接.您会出来更清楚的结尾 -
-
python /em>
其他推荐答案
区别在于:
(a)Python装饰器与现有方法相关,并更改该方法的行为.示例:
@modifyBehavior def original(myString): print myString
原始的行为被覆盖.您不能使用它添加新功能.
(b)装饰物图案是关于多态性的.在上面的示例代码中,装饰器的行为.Something_useful被覆盖.原始方法丢失了.这不是真正的装饰图案.您应该寻求增强或添加功能,而不是替换方法.您应该确保a.something_useful(字符串)返回与B.Something_useful(字符串)相同的东西.实际上,在装饰图案中,您通常会替换原始对象.这是我的意思:
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 withUnderscores(self, string): return '_'.join(string.split(' ')) def __getattr__(self, name): return getattr(self._wrapped, name) if __name__ == '__main__': string = 'Lorem ipsum dolor sit amet.' obj = Class() print('Original: ', obj.something_useful(string)) #This has no underscore function. Use decorator to add. obj = Decorator(obj) print('Replaced spaces: ', obj.withUnderscores(string)) print('Original still works: ', obj.something_useful(string))
您可以有几个装饰器来添加功能.这使您只能在需要时添加所需的内容.更多阅读: gof
问题描述
What is the difference between “Python decorators” and the “decorator pattern”?
When should I use Python decorators, and when should I use the decorator pattern?
I'm looking for examples of Python decorators and the decorator pattern accomplishing same.
@AcceptedAnswer
I know that Jakob Bowyer's answer is valid. Yet it's Srikar's answer that made me understand why.
After Srikar's answer, and studying the given resources, I've written this example, so I can visualize and understand Python decorators and the decorator pattern.
I must disagree with Srikar's "Python decorators are not an implementation of the decorator pattern". After what I've learned, I'm strongly convinced that Python decorators are an implementation of the decorator pattern. Just not in the classic way.
Also, I need to add that, despite the fact that Srikar said "Python decorators add functionality to functions and methods at definition time", you can easily use Python decorators at run time.
Yet, I still mark Srikar's answer as accepted, because it helped me understand the implementation of the decorator pattern in Python.
""" 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
推荐答案
Decorator Pattern - In object-oriented programming, the decorator pattern is a design pattern that allows behaviour to be added to an existing object dynamically. The decorator pattern can be used to extend (decorate) the functionality of a certain object at run-time, independently of other instances of the same class, provided some groundwork is done at design time.
Decorators in Python - Despite the name, Python decorators are not an implementation of the decorator pattern. The decorator pattern is a design pattern used in statically typed object-oriented programming languages to allow functionality to be added to objects at run time; Python decorators add functionality to functions and methods at definition time, and thus are a higher-level construct than decorator-pattern classes.
The decorator pattern itself is trivially implementable in Python, because the language is duck typed, and so is not usually considered as such. So in Python a decorator is any callable Python object that is used to modify a function, method or class definition.
I hope I made the difference clear. Just in case you did not completely understand, please go through these links. You will come out more than clear at the end of it -
其他推荐答案
The difference is this:
(a) Python decorators are tied to an existing method and change the behavior of that method. Example:
@modifyBehavior def original(myString): print myString
The behavior of original is overwritten. You can't use this to add a new functionality.
(b) Decorator pattern is about polymorphism. In your sample code above, the behavior of Decorator.something_useful is overwritten. The original method is lost. It's not really decorator pattern. You should be looking to enhance or add functionality, not replace a method. You should ensure that a.something_useful(string) returns the same thing as b.something_useful(string). In fact, in decorator pattern you would typically replace the original object. Here is what I mean:
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 withUnderscores(self, string): return '_'.join(string.split(' ')) def __getattr__(self, name): return getattr(self._wrapped, name) if __name__ == '__main__': string = 'Lorem ipsum dolor sit amet.' obj = Class() print('Original: ', obj.something_useful(string)) #This has no underscore function. Use decorator to add. obj = Decorator(obj) print('Replaced spaces: ', obj.withUnderscores(string)) print('Original still works: ', obj.something_useful(string))
You can have several decorators to add functionality. This allows you to add only what you need when you need it. More reading: GoF