如何将字符串从函数传递给装饰器?
How to pass string from function into decorator?
我想从函数中获取输入:
def input_text():
text = input('Type the text:\n')
# deco_required = input('Format variable\n')
return text
然后我想要一个装饰器来格式化上面输入的文本:
def center(input_text):
def centering(*args,**kwargs):
t = '<center>{}</center>' .format(kwargs)
return input_text
return centering
我认为这是解决问题的正确方法:
@centring
input_text()
我收到以下错误:
File "<ipython-input-10-95c74b9f0757>", line 2
input_text()
^ SyntaxError: invalid syntax
对我查找帮助不大
首先,如果没有装饰器,您只需将 input_text
的 return 值传递给居中函数即可。
def centering(s):
return '<center>{}</center>'.format(s)
centered_text = centering(input_text)
为您执行此操作的函数可能类似于
def input_centered_text():
text = input('Temp the text:')
centered_text = centering(text)
return centered_text
可以从原始 input_text
生成 input_centered_text
的装饰器看起来像
def center(f):
def _():
centered_text = f()
return centered_text
return _
并像其中一个一样使用
def input_text():
text = input('Type the text:\n')
return text
input_centered_text = center(input_text)
或
@center
def input_centered_text(): # Note the change in the function name
text = input('Type the text:\n')
return text
我想从函数中获取输入:
def input_text():
text = input('Type the text:\n')
# deco_required = input('Format variable\n')
return text
然后我想要一个装饰器来格式化上面输入的文本:
def center(input_text):
def centering(*args,**kwargs):
t = '<center>{}</center>' .format(kwargs)
return input_text
return centering
我认为这是解决问题的正确方法:
@centring
input_text()
我收到以下错误:
File "<ipython-input-10-95c74b9f0757>", line 2
input_text()
^ SyntaxError: invalid syntax
对我查找帮助不大
首先,如果没有装饰器,您只需将 input_text
的 return 值传递给居中函数即可。
def centering(s):
return '<center>{}</center>'.format(s)
centered_text = centering(input_text)
为您执行此操作的函数可能类似于
def input_centered_text():
text = input('Temp the text:')
centered_text = centering(text)
return centered_text
可以从原始 input_text
生成 input_centered_text
的装饰器看起来像
def center(f):
def _():
centered_text = f()
return centered_text
return _
并像其中一个一样使用
def input_text():
text = input('Type the text:\n')
return text
input_centered_text = center(input_text)
或
@center
def input_centered_text(): # Note the change in the function name
text = input('Type the text:\n')
return text