在我的采访中,他们问我一个工具,该工具可以反转句子中的每个单词并从中创建最终句子。例如:
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
使用功能的哪一部分decorator
。他们告诉我使用args
和实现此功能kwargs
,但我无法解决。有人可以帮我吗?如何将任何函数转换为装饰器?
据我所知,您可以decorator
在需要时wrap your function
或想要修改某些功能时使用。我的理解正确吗?
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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句