Python装饰器和继承 [英] Python Decorators and inheritance

查看:254
本文介绍了Python装饰器和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

帮助一个人。似乎无法让装饰器与继承一起工作。将其分解为我的临时工作空间中最简单的小例子。似乎仍然无法正常工作。

Help a guy out. Can't seem to get a decorator to work with inheritance. Broke it down to the simplest little example in my scratch workspace. Still can't seem to get it working.

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

糟糕,名称装饰未定义。

Oops, name "decor" is not defined.

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

Okay, how about @bar.decor? TypeError: unbound method "decor" must be called with a bar instance as first argument (got function instance instead)

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

Ok, how about @self.decor? Name "self" is not defined.

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

Ok, how about @foo.decor?! Name "foo" is not defined.

AaaaAAaAaaaarrrrgggg ...我做错了什么?

AaaaAAaAaaaarrrrgggg... What am I doing wrong?

推荐答案

装饰定义为静态方法,并使用 @ bar.decor 形式:

Define decor as a static method and use the form @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

这篇关于Python装饰器和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆