【发布时间】:2017-01-19 08:14:26
【问题描述】:
我正在阅读有关装饰器的内容,并且从 Simeons blog 那里学到了很多东西,我之前在函数中没有传递参数时取得了成功:装饰器(func)。我认为我的问题是装饰器(func(args))。我认为我的问题是 func(args) 正在执行并将其返回值传递给装饰器而不是函数本身。如何在装饰器中传递函数和参数(示例 B)而不使用 @decorator_name 'decoration' 样式(示例 A)。
编辑:我希望示例 B 产生与示例 A 相同的结果。
user_input = input("Type what you want: ")
def camel_case(func):
def _decorator(arg):
s = ""
words = arg.split()
word_count = len(words)
for i in range(word_count):
if i >0:
s += words[i].title()
else:
s += words[i].lower()
return func(s)
return _decorator
示例 A:可行
@camel_case
def read(text):
print("\n" + text" )
read(user_input)
示例 B:这不起作用
def read(text):
print("\n" + text" )
camel_case(read(user_input))
【问题讨论】:
-
你想达到什么目的?
-
你应该怎么做:
camel_case(read)(user_input) -
刚刚编辑了问题。我希望示例 B 产生与示例 A 相同的结果。