【问题标题】:Can we design any function using a decorator?我们可以使用装饰器设计任何功能吗?
【发布时间】:2026-01-13 10:50:01
【问题描述】:

在我的采访中,他们要求我实现一个函数来反转句子中的每个单词并从中创建最终句子。例如:

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 的功能的哪一部分。他们告诉我使用argskwargs 来实现这个,但我无法解决。有人可以在这里帮助我吗?如何将任何函数转换为装饰器?

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

【问题讨论】:

  • Python - Decorators的可能重复
  • 我不确定我是否理解要执行的任务。装饰师如何提供帮助?
  • 我猜它不是重复的!
  • 你确定他们没有说“发电机”吗?似乎没有任何方式可以让装饰器成为在这里使用的自然工具。
  • 顺便说一下,s[::-1] 是一种更简单的反转字符串的方法。

标签: python decorator python-decorators


【解决方案1】:
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?
  • 你的答案似乎是正确的,你能详细说明一下吗:)
  • 接受您的回答,这似乎是他们正在寻找的方式。谢谢楼主
【解决方案2】:

这是一个不同的例子——它定义了一个装饰器,它接受一个函数,将字符串发送到字符串并返回另一个函数,该函数将传递的函数映射到一个拆分字符串,然后重新加入:

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的?看起来工作量很大
  • 我绝对没有掌握装饰器——但我知道我从 Matt Harrision 的优秀书籍“指南:学习 Python 装饰器”中学到了一些东西。另外——如果你读过函数式编程,你就会意识到装饰器只是 Python 风格的高阶函数。
【解决方案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

【讨论】:

    最近更新 更多