首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将say_whee函数转换为lambda函数?

如何将say_whee函数转换为lambda函数?
EN

Stack Overflow用户
提问于 2020-11-08 00:07:36
回答 1查看 29关注 0票数 0

我想把say_whee变成一个lambda函数。

代码语言:javascript
复制
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_whee():
    print("Whee!")

if __name__ == '__main__':
    say_whee()

我试着这样做,如下所示。但是,它似乎没有调用该函数。

代码语言:javascript
复制
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
(my_decorator(lambda x: print (x))) ("Whee")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-08 00:13:51

Lambda只是编写函数定义的快捷方式。

Lambda版本

代码语言:javascript
复制
say_whee = lambda : print ("Whee")

应用装饰器

代码语言:javascript
复制
say_whee = my_decorator(lambda : print ("Whee"))

完整代码

代码语言:javascript
复制
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

say_whee = my_decorator(lambda : print ("Whee"))

if __name__ == '__main__':
    say_whee()

输出

代码语言:javascript
复制
Something is happening before the function is called.
Whee
Something is happening after the function is called.

为了清楚起见,@装饰器只是应用包装器函数的语法糖。

代码语言:javascript
复制
@my_decorator
def say_whee():
    print("Whee")

等同于

代码语言:javascript
复制
def say_whee():
    print("Whee")
    
say_whee = my_decorator(say_whee)

等同于

代码语言:javascript
复制
say_whee = my_decorator(lambda : print ("Whee"))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64729697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档