python - 我们可以使用装饰器设计任何功能吗?

标签 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_reverse.append("".join(list((reversed(i)))))

    print " ".join(string_reverse)

reverse_sentence(s)

然后他们要求使用装饰器实现相同的功能,我在这里感到困惑。我知道 decorator 的基础知识,它如何使用以及何时使用。他们没有提到他们想要使用 decorator wrap 函数的哪一部分。他们告诉我使用 argskwargs 来实现它,但我无法解决它。有人可以帮我吗?如何将任何函数转换为装饰器?

据我所知,当你想包装你的函数或者你想修改一些功能时,你会使用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/

相关文章:

python - 为什么我的 Python 装饰器类的 __get__ 方法不是在所有情况下都被调用?

python - 通过关联值的函数过滤字典键

python - 如何按类别绘制平均值条形图

python - matplotlib - 调用axes.cla()后,autofmt_xdate()无法旋转x轴标签

python - 如何通过装饰器获取底层函数参数信息?

python - 以编程方式更改类对象的文档字符串

python - 如何使用 NLTK 分词器去除标点符号?

Python 内存/延迟查找属性装饰器

python - 如何使用装饰器将变量注入(inject)范围?

python - 如何用装饰器绕过python函数定义?