【发布时间】:2018-08-15 00:20:18
【问题描述】:
我在使用一个类来装饰另一个类的方法时遇到问题。代码如下:
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)
显示这个错误
TypeError: func() takes exactly 3 arguments (2 given).
如果调用使用:
t.func(t, 1, 2)
然后它通过了。但是如果装饰器被拿走,那么这条线就会再次出现问题。
为什么会发生这种情况以及如何解决?
编辑:在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, self.y
t = test()
t.func()
这显示了同样的错误。但是
t.func(t)
有效但不理想。
【问题讨论】:
标签: python class methods decorator