在python中如何使staticmethod作为decorator?

2024-10-02 00:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

在用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?在

提前谢谢。在


Tags: 代码objsearchreturnobjectdefargrequired
2条回答

经过一番挖掘,我发现staticmethod对象有__func__内部变量__func__,它存储要执行的原始函数。在

所以,下面的解决方案对我有效:

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

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

相关问题 更多 >

    热门问题