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

标签 python decorator

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

我(错误地)假设 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'

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

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


    @_deco
    def meh(self):
        print 'I\'m a function'

这甚至无法正确导入,更不用说运行了。 @_deco 未定义。尝试 baseclass._deco 会引发未绑定(bind)方法 _deco() 错误,这并不奇怪。

知道如何做到这一点,我真的很想将装饰器封装在类中,但我没有接受这个想法,我需要在基类和子类中调用它。

最佳答案

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'

    @_deco
    def basefunc2(self):
        print "I'm another base function"

   #no more uses of _deco in this class
    _deco = staticmethod(_deco) 
   # this is the key. it must be executed after all of the uses of _deco in 
   # the base class. this way _deco is some sort weird internal function that 
   # can be called from within the class namespace while said namespace is being 
   # created and a proper static method for subclasses or external callers.


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


    @baseclass._deco
    def meh(self):
        print 'I\'m a function'

关于python - 在 Python 中从子类访问父类中的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3421337/

相关文章:

python - 如何返回每个分类实例的概率?

python - 如何使用 Pandas 中的输入语料库/列表从列中提取所有字符串匹配项?

python - SQLAlchemy delete() 函数刷新,但不提交,即使在调用 commit() 之后

python - 具有 Statsmodel ValueError : zero-size array to reduction operation maximum which has no identity 的多重 OLS 回归

java - 抽象装饰器类而不是装饰器中的功能

java - 装饰器设计模式不明确

python - 复制的旧列表引用被 python 中的新列表对象修改所更改

python - 在不使用临时文件的情况下通过 __get__ 调用 __iadd__ 时发生内存泄漏

python - 为什么装饰器必须在调用之前声明,而函数却不需要?

php - PHP 中伪造方法属性?