デコレータを学習しようとしているので、特定のタグ内にコンテンツを作成しようとしている次の例を実装しました。デコレータ関数が2つの引数をとるときのデコレータ
def content_decoration(func1):
def inner_function(name, c_decorator, tag):
return '<{1}> {0} </{1}>'.format(func1(name, c_decorator), tag)
return inner_function
@content_decoration
def return_decorated_content(content , con_decorator):
return '{0} {1}'.format(content, con_decorator)
return_decorated_content('Content', ' content_addition', 'p')
上記のコマンドの出力は次のようになります。 '<p> Content content_addition </p>'
私はコンテンツとタグ自体の両方を飾るために必要がある場合、私は、それは少し難しいが。
def decoration(func1, func2):
def inner_function(content, tag, content_decoration=None, tag_decoration=None):
return '<{1}> {0} </{1}>'.format(func1(content, content_decoration), func2(tag, tag_decoration))
return inner_function
def name_decoration(con, con_decor):
return '{0} {1}'.format(con, con_decor)
def tag_decoration(tag, tag_decor):
return '{0} {1}'.format(tag, tag_decor)
デコレータを使用しないと、我々が持っているでしょう:
print decoration(name_decoration, tag_decoration)(content='Alice', tag='h1', tag_decoration='fontsize=12', content_decoration='')
# or
print
function = decoration(name_decoration, tag_decoration)
print function(content='Bob', content_decoration='Smith', tag='p')
得られます。たとえば、我々は次のコードを持っている
<h1 fontsize=12> Alice </h1 fontsize=12>
<p None> Bob Smith </p None>
をどのように私は、同じ結果を得ることができますPythonの構文的な砂糖を使用して?
おそらく重複: https://stackoverflow.com/q/5929107/1256452 – torek
[パラメータ付きデコレータの可能な複製?](https://stackoverflow.com/questions/5929107/decorators-with-parameters) –