小编Jac*_*cky的帖子

使用类作为另一个类的方法的装饰器

我在使用一个类来装饰另一个类的方法时遇到问题。代码如下:

class decorator(object):
    def __init__(self, func):
        self.func = func

    def __call__(self, *args):
        return self.func(*args)

class test(object):
    @decorator
    def func(self, x, y):
        print x, y

t = test()
t.func(1, 2)
Run Code Online (Sandbox Code Playgroud)

它显示这个错误

TypeError: func() takes exactly 3 arguments (2 given).
Run Code Online (Sandbox Code Playgroud)

如果使用以下方式调用:

t.func(t, 1, 2)
Run Code Online (Sandbox Code Playgroud)

然后它就过去了。但如果装饰器被拿走,那么这条线又会出现问题。

为什么会发生这种情况以及如何解决?

编辑:显示自我的代码的第二个版本decorator.__call__应该与以下自我不同test.func

class decorator(object):
    def __init__(self, func):
        self.func = func

    def __call__(self, *args):
        return self.func(*args)

class test(object):
    def __init__(self):
        self.x = 1
        self.y = 2
    @decorator
    def func(self):
        print self
        print self.x, …
Run Code Online (Sandbox Code Playgroud)

python methods class decorator

2
推荐指数
1
解决办法
646
查看次数

标签 统计

class ×1

decorator ×1

methods ×1

python ×1