Python装饰器和继承
帮助一个人。似乎无法让装饰师处理继承。将其分解为我的scratch工作区中最简单的小示例。似乎仍然无法让它工作Python装饰器和继承,python,inheritance,decorator,Python,Inheritance,Decorator,帮助一个人。似乎无法让装饰师处理继承。将其分解为我的scratch工作区中最简单的小示例。似乎仍然无法让它工作 class bar(object): def __init__(self): self.val = 4 def setVal(self,x): self.val = x def decor(self, func): def increment(self, x): return func( s
class bar(object):
def __init__(self):
self.val = 4
def setVal(self,x):
self.val = x
def decor(self, func):
def increment(self, x):
return func( self, x ) + self.val
return increment
class foo(bar):
def __init__(self):
bar.__init__(self)
@decor
def add(self, x):
return x
哦,没有定义名称“装饰”
好的,那装饰条怎么样?TypeError:必须使用bar实例作为第一个参数调用未绑定的方法“decor”(取而代之的是函数实例)
好的,你觉得self.decor怎么样?未定义名称“self”
好的,那么@foo.decor
呢?!未定义名称“foo”
aaaaaaaaaarrrgggg。。。我做错了什么?将
decor
定义为静态方法,并使用@bar.decor
:
class bar(object):
def __init__(self):
self.val = 4
def setVal(self,x):
self.val = x
@staticmethod
def decor(func):
def increment(self, x):
return func(self, x) + self.val
return increment
class foo(bar):
def __init__(self):
bar.__init__(self)
@bar.decor
def add(self, x):
return x
在您的示例中,您可以在
foo
中使用return x+self.val
来定义add
。你能不能在你的实际代码中做到这一点?这是一个经过提炼的示例代码,突出了我所面临的问题。如果代码那么简单,那么是的。然而,事实并非如此。这更有效,因为两个函数定义中都没有使用self
。@EShull:实际上,decor
可以是静态方法,尽管有self
引用self
仅在increment()
中引用,并且在foo
实例上调用f.add(10)
时,increment()
中的self
参数将引用f
,增量将按预期工作。看起来它会工作。我得离开工作,但如果真的离开了,我会把这当作答案。谢谢这目前有效吗?它是否不会引发类型错误:staticmethod不可调用
?