如何将 class 中的静态方法作为 python 中的装饰器?
How to make staticmethod in the class as decorator in python?
我在 python 中创建装饰器时遇到了一个有趣的场景。以下是我的代码:-
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)
如上面的代码所示,我创建了一个装饰器(class 中的静态方法),它检查 "obj_user" 是否作为参数传递给装饰函数。我已经装饰函数 find_father
,但我收到以下错误消息:- 'staticmethod' object is not callable
.
如何使用如上所示的静态实用方法,作为 python 中的装饰器?
提前致谢。
staticmethod
是一个 描述符 。 @staticmethod
return 描述符对象而不是 function
。这就是为什么它会引发 staticmethod' object is not callable
.
我的回答是避免这样做。我认为没有必要将 user_arg_required
设为静态方法。
经过一些尝试,我发现如果你仍然想使用静态方法作为装饰器,有 hack。
@staticmethod
@user_arg_required.__get__(0)
def find_father(**search_params):
return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params)
这篇文档会告诉你什么是描述符。
深入挖掘后,我发现,staticmethod 对象有 __func__
内部变量 __func__
,它存储要执行的原始函数。
所以,以下解决方案对我有用:-
@staticmethod
@user_arg_required.__func__
def find_father(**search_params):
return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params)
我在 python 中创建装饰器时遇到了一个有趣的场景。以下是我的代码:-
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)
如上面的代码所示,我创建了一个装饰器(class 中的静态方法),它检查 "obj_user" 是否作为参数传递给装饰函数。我已经装饰函数 find_father
,但我收到以下错误消息:- 'staticmethod' object is not callable
.
如何使用如上所示的静态实用方法,作为 python 中的装饰器?
提前致谢。
staticmethod
是一个 描述符 。 @staticmethod
return 描述符对象而不是 function
。这就是为什么它会引发 staticmethod' object is not callable
.
我的回答是避免这样做。我认为没有必要将 user_arg_required
设为静态方法。
经过一些尝试,我发现如果你仍然想使用静态方法作为装饰器,有 hack。
@staticmethod
@user_arg_required.__get__(0)
def find_father(**search_params):
return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params)
这篇文档会告诉你什么是描述符。
深入挖掘后,我发现,staticmethod 对象有 __func__
内部变量 __func__
,它存储要执行的原始函数。
所以,以下解决方案对我有用:-
@staticmethod
@user_arg_required.__func__
def find_father(**search_params):
return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params)