2010-06-08 134 views
15

帮助一个人。似乎无法得到装饰工作与继承。将其分解成我的临时工作区中最简单的示例。仍似乎无法得到它的工作。Python装饰器和继承

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 

糟糕,名称“装饰”未定义。

好的,@bar.decor怎么样? TypeError:必须用bar实例作为第一个参数调用unbound方法“decor”(取而代之的是函数实例)

好的,@self.decor怎么样?名称“自我”未定义。

好的,@foo.decor怎么样?!名称“foo”未定义。

AaaaAAaAaaaarrrrgggg ...我做错了什么?

+0

在你的榜样,你可以有'返回X + self.val'在'foo'的add'的'定义。你能不能在你的实际代码中做到这一点? – 2010-06-08 20:52:16

+0

这是一个精炼的示例代码,突出显示了我正面临的问题。如果代码很简单,那么是的。但是,事实并非如此。 – wheaties 2010-06-08 21:04:10

回答

19

定义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 
+0

这可以更好地发挥作用,因为在两个函数定义中都不使用'self'。 – exupero 2010-06-08 21:00:03

+1

@eshull:实际上,'decor'可以是一个静态方法,尽管有'self'引用。 'self'只在'increment()'内被引用,并且在'foo'实例上调用'f.add(10)'时,'increment()'中的'self'参数会引用'f',增量将按预期工作。 – 2010-06-08 21:07:36

+0

这看起来像它会工作。要离开工作,但如果是这样,我将以此为答案。谢谢! – wheaties 2010-06-08 21:23:23