在Python中从子级访问父类中的装饰器 [英] Accessing a decorator in a parent class from the child in Python

查看:128
本文介绍了在Python中从子级访问父类中的装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

how does one go about accessing a decorator from a base class in a child?

我(错误地)认为ffg。会起作用:

I assumed (wrongly) that the ffg. would work:

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'

该类工作正常,但是我创建了一个子类

This class works fine, but then I create a child class inheriting from this:

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会引发未绑定的方法_deco()错误,这并不令人惊讶。

This won't even import properly, let alone run. @_deco is undefined. Trying baseclass._deco throws an unbound method _deco() error, which isn't really surprising.

任何想法如何做到这一点,我真的想封装类中的装饰器,但我对这个主意不满意,需要在基础&子级类。

Any idea how to do this, I'd really like to encapsulate the decorator in the class, but I'm not married to the idea and I'd need to call it in the base & the child class.

推荐答案

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中从子级访问父类中的装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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