2017-02-26 85 views
2

我遇到了一个有趣的场景,同时在python中创建装饰器。以下是我的代码: -如何使类中的staticmethod作为装饰器在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) 

如上面的代码所示,我创建了一个装饰(这是在类的静态方法),检查,如果“obj_user”作为参数传递给装饰函数传递。我已装饰功能find_father,但我收到以下错误消息: - 'staticmethod' object is not callable

如何使用上面显示的静态工具方法作为python中的装饰器?

在此先感谢。

+1

这是否回答帮助? http://stackoverflow.com/a/6412373/4014959 –

回答

2

staticmethod描述符@staticmethod返回描述符对象而不是function。那为什么它提出staticmethod' object is not callable

我的答案是简单地避免这样做。我不认为有必要使user_arg_required成为一种静态方法。

经过一番游戏后,我发现如果你仍然想使用静态方法作为装饰器,那么就有黑客入侵。

@staticmethod 
@user_arg_required.__get__(0) 
def find_father(**search_params): 
    return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params) 

此文档将告诉您什么是描述符。

https://docs.python.org/2/howto/descriptor.html

0

挖一点后,我发现,静态方法对象具有__func__内部变量__func__,其存储将要执行的原始功能。

所以,下面的解决方案为我工作: -

@staticmethod 
@user_arg_required.__func__ 
def find_father(**search_params): 
    return RelationShipSearchMgr.search(Relation.RELATION_FATHER, **search_params)