我在使用一个类来装饰另一个类的方法时遇到问题。代码如下
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)
它显示这个错误
类型错误:func() 正好接受 3 个参数(给出 2 个)。
如果调用使用
t.func(t, 1, 2)
然后它通过。但是如果装饰器被带走,那么这条线将再次出现问题。
为什么会发生这种情况以及如何解决?
编辑:在装饰器中显示自我的代码的第二个版本。call应该与 test.func 中的 self 不同
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)
有效但不理想。
要作为方法工作,类中的对象需要实现描述符协议的一部分。也就是说,它应该有一个__get__
方法返回一个可调用对象,该对象已“绑定”到该方法所查找的实例。
这是您可以使用包装函数完成这项工作的一种方法:
class decorator(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
def wrapper(*args):
return self.func(instance, *args) # note, self here is the descriptor object
return wrapper
您可以改为从 返回某个其他类的实例__get__
,而不是函数,并使用该__call__
其他类的方法来实现包装器。但是,如果您没有使用闭包,则需要将instance
显式传递给包装类(以及函数,因为self.func
在描述符类之外无法工作)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句