【问题标题】:How to make staticmethod in the class as decorator in python?如何将类中的staticmethod作为python中的装饰器?
【发布时间】:2017-07-16 19:55:03
【问题描述】:

我在 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中的装饰器?

提前致谢。

【问题讨论】:

标签: python decorator static-methods


【解决方案1】:

staticmethod 是一个描述符@staticmethod 返回描述符对象而不是 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)

这个文档会告诉你什么是描述符。

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

【讨论】:

    【解决方案2】:

    挖了一下发现,staticmethod对象有__func__内部变量__func__,里面存放了要执行的原始函数。

    所以,以下解决方案对我有用:-

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

    【讨论】:

      猜你喜欢
      • 2017-11-01
      • 2020-05-23
      • 2021-04-12
      • 2012-04-11
      • 1970-01-01
      • 2021-07-16
      • 2015-01-03
      • 2022-01-21
      • 2019-09-20
      相关资源
      最近更新 更多