【发布时间】:2018-01-02 06:51:06
【问题描述】:
如果我创建如下装饰器:
def my_decorator(some_fun):
def wrapper():
print("before some_function() is called.")
some_fun()
print("after some_function() is called.")
return wrapper
@my_decorator
def just_some_function():
print("Wheee!")
另一个装饰器可以定义为:
def my_decorator(some_fun):
print("before some_function() is called.")
some_fun()
print("after some_function() is called.")
@my_decorator
def just_some_fun():
print("some fun")
两个装饰器的工作方式相同。在装饰器中使用“包装器”功能有什么好处。我没明白目的。
【问题讨论】:
-
你试过了吗?这两个代码块对我来说产生了完全不同的结果。
-
真的吗?您是否尝试在第二个代码块中调用
just_some_fun()?是的,当my_decorator被just_some_fun调用时,东西会被打印出来,但是当你调用just_some_fun()它会随着TypeError: 'NoneType' object is not callable而崩溃。 -
“两个装饰器的工作方式相同”——你对这个断言有什么支持吗?
-
打印是一种副作用,与返回对象不同。在不使用
print()的情况下尝试类似的操作,例如修改字符串。你将不得不返回一些东西。
标签: python python-3.x python-decorators