装饰设置的功能属性 [英] decorator to set attributes of function
问题描述
我想不同的功能,可执行只有在登录的用户具有所需的权限级别。
I want different functions to be executable only if the logged in user has the required permission level.
为了让我的生活更简单复杂地我想用装饰。下面我attempy设置属性许可
在'装饰'的功能 - 如下图所示。
To make my life more complexly simply I want to use decorators. Below I attempy to set attribute permission
on 'decorated' functions - as shown below.
def permission(permission_required):
def wrapper(func):
def inner(*args, **kwargs):
setattr(func, 'permission_required', permission_required)
return func(*args, **kwargs)
return inner
return wrapper
@permission('user')
def do_x(arg1, arg2):
...
@permission('admin')
def do_y(arg1, arg2):
...
但是,当我做的:
But when I do:
fn = do_x
if logged_in_user.access_level == fn.permission_required:
...
我得到一个错误'功能'对象有没有属性'permission_required
我是什么失踪?
推荐答案
您在设置于内(包装)函数的属性。你并不需要一个包装函数的所有的:
You are setting the attribute in the inner (wrapper) function. You don't need a wrapper function at all:
def permission(permission_required):
def decorator(func):
func.permission_required = permission_required
return func
return decorator
您装饰需要返回的的东西的那会取代原来的功能。原函数本身(与添加的属性)会做得很好的,因为你想要做的一切是添加属性给它。
Your decorator needs to return something that'll replace the original function. The original function itself (with the attribute added) will do fine for that, because all you wanted to do is add an attribute to it.
如果您仍需要一个包装,然后设置该属性上的包装函数的代替:
If you still need a wrapper, then set the attribute on the wrapper function instead:
def permission(permission_required):
def decorator(func):
def wrapper(*args, **kwargs):
# only use a wrapper if you need extra code to be run here
return func(*args, **kwargs)
wrapper.permission_required = permission_required
return wrapper
return decorator
毕竟,您要更换由装饰返回的包装包装的功能,所以这是你要寻找的该属性的对象。
After all, you are replacing the wrapped function with the wrapper returned by the decorator, so that's the object you'll be looking for the attribute on.
这篇关于装饰设置的功能属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!