当使用多个装饰器时,有没有办法获取原始函数的返回值? 这是我的装饰者:
def format_print(text):
def wrapper():
text_wrap = """
**********************************************************
**********************************************************
"""
print(text_wrap)
text()
print(text_wrap)
return wrapper
def role_required(role):
def access_control(view):
credentials = ['user', 'supervisor']
def wrapper(*args, **kwargs):
requested_view = view()
if role in credentials:
print('access granted')
return requested_view
else:
print('access denied')
return '/home'
return wrapper
return access_control
当我使用@role_required 运行下面的函数时,我得到了我所期望的:
@role_required('user')
def admin_page():
print('attempting to access admin page')
return '/admin_page'
x = admin_page()
print(x)
返回:
attempting to access admin page
access granted
/admin_page
但是当我取消注释第二个装饰器时,admin_page() 返回 None
**********************************************************
**********************************************************
attempting to access admin page
access granted
**********************************************************
**********************************************************
None
有人能告诉我哪里出错了,以及如何从具有多个装饰器的函数中获取返回值。
非常感谢
答案 0 :(得分:1)
这是因为您确实需要这样做:
def format_print(text):
def wrapper():
text_wrap = """
**********************************************************
**********************************************************
"""
print(text_wrap)
result = text()
print(text_wrap)
return result
return wrapper
否则您的包装器将始终返回 None
。