在我的采访中,他们要求我实现一个函数来反转句子中的每个单词并从中创建最终句子。例如:
s = 'my life is beautiful'
output - `ym efil si lufituaeb`
我知道这个问题很简单所以几分钟就解决了:
s = 'my life is beautiful'
def reverse_sentence(s):
string_reverse = []
for i in s.split():
string_reverse.append("".join(list((reversed(i)))))
print " ".join(string_reverse)
reverse_sentence(s)
然后他们要求使用装饰器
实现相同的功能,我在这里感到困惑。我知道 decorator
的基础知识,它如何使用以及何时使用。他们没有提到他们想要使用 decorator
wrap
函数的哪一部分。他们告诉我使用 args
和 kwargs
来实现它,但我无法解决它。有人可以帮我吗?如何将任何函数转换为装饰器?
据我所知,当你想包装你的函数
或者你想修改一些功能时,你会使用decorator
。我的理解正确吗?
最佳答案
def reverse_sentence(fn): # a decorator accepts a function as its argument
def __inner(s,*args,**kwargs): #it will return this modified function
string_reverse = []
for i in s.split():
string_reverse.append("".join(list((reversed(i)))))
return fn(" ".join(string_reverse),*args,**kwargs)
return __inner # return the modified function which does your string reverse on its first argument
我猜...
@reverse_sentence
def printer(s):
print(s)
printer("hello world")
关于python - 我们可以使用装饰器设计任何功能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33683912/