我们能用装饰器设计任何函数吗?

2024-05-14 18:56:04 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的采访中,他们要求我实现一个函数,将句子中的每个单词颠倒过来,并由此生成最后一个句子。例如:

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它是怎么用的,什么时候用的。他们没有提到要使用decoratorwrap函数的哪个部分。他们告诉我用argskwargs来实现这个,但我没能解决这个问题。有人能帮我吗?如何将任何函数转换为decorator?你知道吗

据我所知,当您想wrap your function或想修改某些功能时,可以使用decorator。我的理解正确吗?你知道吗


Tags: 函数outputstringismydecorator单词sentence
3条回答

这个怎么样:

# 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,它接受一个函数,该函数将字符串发送到字符串,并返回另一个函数,该函数将传递的函数映射到拆分的字符串上,然后重新联接:

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'
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")

相关问题 更多 >

    热门问题