"Pythonデコレータ"と "デコレータパターン"の違いは何ですか?Pythonデコレータとデコレータパターンの違いは何ですか?
私はいつPythonデコレータを使うべきですか?デコレータパターンはいつ使うべきですか?
私はPythonデコレータとデコレータパターンの例を探していますか?
@AcceptedAnswer
私はJakob Bowyer's answerが有効であることを知っています。それでも私が理由を理解できるStrikarの答えです。
Srikarさんの答えとリソースを勉強した後、私はこの例を書いたので、私はPythonデコレータとDecoratorパターンを視覚化して理解することができます。
私はStrikarのでを同意しなければならない「Pythonのデコレータは、Decoratorパターンの実装ではありません」。私が学んだことの後で私は、Pythonデコレータがデコレータパターンの実装であると強く確信しています。ちょうど古典的な方法ではありません。
または、私がStrikarはあなたが簡単に実行時でPytohonデコレータを使用することができます「Pythonのデコレータは、定義時で関数やメソッドに機能を追加する」と述べたという事実にもかかわらず、ことを追加する必要があります。しかし
受け入れて、それは私がPythonのでDecoratorパターンのImplementationを理解して助けたので、私はまだ、Stikerの答えをマーク。
"""
Testing Python decorators against 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 functioon
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 Decorator Pattern
@スリカールは正しいです。あなたは面白いと思うかもしれない[ここ](http://stackoverflow.com/q/3118929/146792)の別の質問です! – mac
@Srikar、私は受け入れることができません質問に記載された問題を解決しないSnswerを受け入れることはできません。申し訳ありませんが、私の質問の提案された解決法のほとんどは機能しません。 – seler
@seler fair enough。 –