小编and*_*iev的帖子

装饰器类和缺少必需的位置参数

我在包装类方面遇到问题,并且无法弄清楚我做错了什么。我如何让该包装器与带有“self”参数的任何类函数一起使用?

这是针对 Python 3.7.3 的。问题是我记得包装器以前工作过,但似乎有些东西发生了变化……也许我现在只是做了一些错误的事情,而以前没有。

class SomeWrapper:

    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        # this fails because self is not passed
        # ERROR: __init__() missing 1 required positional argument: 'self'
        func_ret = self.func(*args, **kwargs)

        # this is also wrong, because that's the wrong "self"
        # ERROR: 'SomeWrapper' object has no attribute 'some_func'
        # func_ret = self.func(self, *args, **kwargs)

        return func_ret


class SomeClass:

    SOME_VAL = False

    def __init__(self):
        self.some_func()
        print("Success")

    @SomeWrapper
    def some_func(self):
        self.SOME_VAL = True

    def …
Run Code Online (Sandbox Code Playgroud)

python callable decorator python-decorators

6
推荐指数
1
解决办法
4113
查看次数

标签 统计

callable ×1

decorator ×1

python ×1

python-decorators ×1