代码之家  ›  专栏  ›  技术社区  ›  wheaties

python装饰和继承

  •  16
  • wheaties  · 技术社区  · 16 年前

    帮帮一个人。似乎找不到装修师来处理继承。把它分解成我的草稿工作区中最简单的一个小例子。似乎仍然无法使它正常工作。

    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
    

    糟糕,没有定义名称“decor”。

    好吧,怎么样? @bar.decor ?类型错误:必须使用bar实例作为第一个参数调用未绑定的方法“decor”(改为获取函数实例)

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

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

    aaaaaaaaaarrggg…我做错什么了?

    1 回复  |  直到 16 年前
        1
  •  20
  •   Pär Wieslander    16 年前

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