Jac*_*cky 2 python methods class decorator
我在使用一个类来装饰另一个类的方法时遇到问题。代码如下:
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, self.y
t = test()
t.func()
Run Code Online (Sandbox Code Playgroud)
这显示了相同的错误。但
t.func(t)
Run Code Online (Sandbox Code Playgroud)
有效但不理想。
要作为方法工作,类中的对象需要实现描述符协议的一部分。也就是说,它应该有一个__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
Run Code Online (Sandbox Code Playgroud)
您可以从 返回某个其他类的实例__get__(而不是函数),并使用__call__该其他类的方法来实现包装器。如果您不使用闭包,则需要instance显式地将 传递给包装类(以及函数,因为self.func在描述符类之外不起作用)。
| 归档时间: |
|
| 查看次数: |
646 次 |
| 最近记录: |