2017-12-29 6 views
0

デコレータを学習しようとしているので、特定のタグ内にコンテンツを作成しようとしている次の例を実装しました。デコレータ関数が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の構文的な砂糖を使用して?

+0

おそらく重複: https://stackoverflow.com/q/5929107/1256452 – torek

+0

[パラメータ付きデコレータの可能な複製?](https://stackoverflow.com/questions/5929107/decorators-with-parameters) –

答えて

1

あなたが飾られる関数上記nametag関数を宣言し、外デコレータにパラメータとして渡すことができます。

def decoration(func1, func2): 
    def wrapper(f1): 
    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 
    return wrapper 

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) 

@decoration(name_decoration, tag_decoration) 
def get_html(content, tag, content_decoration=None, tag_decoration=None): 
    return 

print(get_html(content='Alice', tag='h1', tag_decoration='fontsize=12', content_decoration='')) 
print(get_html(content='Bob', content_decoration='Smith', tag='p')) 

出力:

<h1 fontsize=12> Alice </h1 fontsize=12> 
<p None> Bob Smith </p None> 

それとも、あなたがlambda機能を使用することができますスペースを節約するために:

@decoration(lambda con, con_decor:'{0} {1}'.format(con, con_decor), lambda tag, tag_decor:'{0} {1}'.format(tag, tag_decor)) 
def get_html(content, tag, content_decoration=None, tag_decoration=None): 
    return 
+0

すばらしい、ありがとう!! – thanasissdr

関連する問題