我想把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")发布于 2020-11-08 00:13:51
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"))https://stackoverflow.com/questions/64729697
复制相似问题