Python 我们可以使用装饰器设计任何函数吗?
在我的采访中,他们要求我实现一个函数,将句子中的每个单词颠倒过来,并由此生成最后一个句子。例如:Python 我们可以使用装饰器设计任何函数吗?,python,decorator,python-decorators,Python,Decorator,Python Decorators,在我的采访中,他们要求我实现一个函数,将句子中的每个单词颠倒过来,并由此生成最后一个句子。例如: 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_r
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
如何使用以及何时使用的基本知识。他们没有提到要使用装饰器包装函数的哪个部分。他们告诉我使用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")
这里有一个不同的例子——它定义了一个decorator,该decorator接受一个函数,该函数将字符串发送到字符串,并返回另一个函数,该函数将传递的函数映射到拆分字符串上,然后重新联接:
def string_map(f): #accepts a function on strings, splits the string, maps the function, then rejoins
def __f(s,*args,**kwargs):
return " ".join(f(t,*args,**kwargs) for t in s.split())
return __f
@string_map
def reverse_string(s):
return s[::-1]
典型输出:
>>> reverse_string("Hello World")
'olleH dlroW'
这个怎么样:
# decorator method
def my_decorator(old_func):
def new_func(*args):
newargs = (' '.join(''.join(list(args[0])[::-1]).split()[::-1]),)
old_func(*newargs) # call the 'real' function
return new_func # return the new function object
@my_decorator
def str_rev(mystr):
print mystr
str_rev('my life is beautiful')
# ym efil si lufituaeb
可能重复我不确定我是否理解要执行的任务。一个装潢师能帮上什么忙呢?我想这不是复制品!你确定他们没有说“发电机”吗?在这里,似乎没有任何方式可以让decorator成为一种自然的工具。顺便说一句,s[:-1]
将是一种更简单的方法来反转字符串。为什么在这里使用@decorator?你的答案似乎是正确的,请你再详细说明一下:)接受你的答案,这似乎是他们正在寻找的方式。谢谢你,先生,你们是怎么掌握装饰师的?看起来有这么多的工作我肯定还没有掌握decorators——但我所知道的是我从Matt Harrison的优秀著作《学习Python decorators指南》中学到的。另外,如果您阅读了一些函数式编程的知识,那么您就会意识到装饰器只是Python风格的高阶函数。