如何将 say_whee 函数转换为 lambda?
How do I turn the say_whee function into a lambda?
我想将 say_whee
变成 lambda 函数。
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()
我试过这样做,如下所示。不过好像没有调用函数。
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")
Lambda 只是编写函数定义的快捷方式。
Lambda 版本
say_whee = lambda : print ("Whee")
应用装饰器
say_whee = my_decorator(lambda : print ("Whee"))
完整代码
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()
输出
Something is happening before the function is called.
Whee
Something is happening after the function is called.
为清楚起见,@
装饰器只是应用包装函数的语法糖。
这个
@my_decorator
def say_whee():
print("Whee")
与
相同
def say_whee():
print("Whee")
say_whee = my_decorator(say_whee)
与
相同
say_whee = my_decorator(lambda : print ("Whee"))
我想将 say_whee
变成 lambda 函数。
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()
我试过这样做,如下所示。不过好像没有调用函数。
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")
Lambda 只是编写函数定义的快捷方式。
Lambda 版本
say_whee = lambda : print ("Whee")
应用装饰器
say_whee = my_decorator(lambda : print ("Whee"))
完整代码
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()
输出
Something is happening before the function is called.
Whee
Something is happening after the function is called.
为清楚起见,@
装饰器只是应用包装函数的语法糖。
这个
@my_decorator
def say_whee():
print("Whee")
与
相同def say_whee():
print("Whee")
say_whee = my_decorator(say_whee)
与
相同say_whee = my_decorator(lambda : print ("Whee"))