在用python创建decorator时,我遇到了一个有趣的场景。以下是我的代码:
class RelationShipSearchMgr(object):
@staticmethod
def user_arg_required(obj_func):
def _inner_func(**kwargs):
if "obj_user" not in kwargs:
raise Exception("required argument obj_user missing")
return obj_func(*tupargs, **kwargs)
return _inner_func
@staticmethod
@user_arg_required
def find_father(**search_params):
return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params)
如上面的代码所示,我创建了一个decorator(它是类中的静态方法),它检查“obj_user”是否作为参数传递给修饰函数。我已经修饰了函数find_father
,但是我得到了以下错误消息:-'staticmethod' object is not callable
。在
如何使用上面所示的静态实用程序方法,作为python中的decorator?在
提前谢谢。在
经过一番挖掘,我发现staticmethod对象有
__func__
内部变量__func__
,它存储要执行的原始函数。在所以,下面的解决方案对我有效:
staticmethod
是一个描述符。@staticmethod
返回描述符对象而不是function
。这就是为什么它会升高staticmethod' object is not callable
。在我的回答是避免这样做。我认为没有必要使
user_arg_required
成为静态方法。在经过一番周折,我发现如果你还想用静态方法作为装饰器,那就有黑客了。在
这个文件会告诉你什么是描述符。在
https://docs.python.org/2/howto/descriptor.html
相关问题 更多 >
编程相关推荐