【发布时间】:2018-06-07 14:55:33
【问题描述】:
我有一个这样的方法装饰器。
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)
如何将参数传递给装饰器类,为什么它会覆盖方法?
【问题讨论】:
标签: python