相关疑难解决方法(0)

在Python中从子级访问父类中的装饰器

如何从孩子的基类访问装饰器?

我(错误地)假设了ffg.会工作:

class baseclass(object):
    def __init__(self):
        print 'hey this is the base'

    def _deco(func):
        def wrapper(*arg):
            res = func(*arg)
            print 'I\'m a decorator. This is fabulous, but that colour, so last season sweetiedarling'
            return res
        return wrapper

    @_deco
    def basefunc(self):
        print 'I\'m a base function'
Run Code Online (Sandbox Code Playgroud)

这个类工作正常,但后来我创建了一个继承自这个的子类:

class otherclass(baseclass):
    def __init__(self):
        super(otherclass, self).__init__()
        print 'other class'


    @_deco
    def meh(self):
        print 'I\'m a function'
Run Code Online (Sandbox Code Playgroud)

这甚至不能正确导入,更不用说运行了.@_deco未定义.尝试baseclass._deco抛出一个未绑定的方法_deco()错误,这并不奇怪.

任何想法如何做到这一点,我真的想把装饰器封装在课堂上,但我没有嫁给这个想法,我需要在基础和子类中调用它.

python decorator

8
推荐指数
1
解决办法
2095
查看次数

标签 统计

decorator ×1

python ×1