我有一个像这样的方法装饰器。
如何向装饰器类传递参数,为什么它会覆盖该方法?
class MyClass:
def __init__(self):
self.start = 0
class Decorator:
def __init__(self, f):
self.f = f
self.msg = msg
def __get__(self, instance, _):
def wrapper(test):
print(self.msg)
print(instance.start)
self.f(instance, test)
return self.f
return wrapper
@Decorator
def p1(self, sent):
print(sent)
c = MyClass()
c.p1('test')
这个方法很好用。但是,如果我想要向装饰器传递一个参数,方法就不再作为参数传递,并且会出现以下错误:
TypeError: init()缺少1个位置参数:'f'
class MyClass:
def __init__(self):
self.start = 0
class Decorator:
def __init__(self, f, msg):
self.f = f
self.msg = msg
def __get__(self, instance, _):
def wrapper(test):
print(self.msg)
print(instance.start)
self.f(instance, test)
return self.f
return wrapper
@Decorator(msg='p1')
def p1(self, sent):
print(sent)
@Decorator(msg='p2')
def p2(self, sent):
print(sent)
如何向装饰器类传递参数,为什么它会覆盖该方法?
__call__
方法需要返回self
,否则装饰器语法会将方法替换为None
(显然这是没有用的)。 - Blckknght