Доступ к декоратору в родительском классе из дочернего элемента в Python

как можно получить доступ к декоратору из базового класса у ребенка?

Я предположил (ошибочно) что ффг. должно сработать:

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 выдает ошибку несвязанного метода _deco (), что неудивительно.

Любая идея, как это сделать, я бы очень хотел заключить в класс декоратор, но я не женат на идея, и мне нужно было бы назвать ее в базовом и дочернем классе.

8
задан dochead 6 August 2010 в 07:00
поделиться

1 ответ

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'
10
ответ дан 5 December 2019 в 17:33
поделиться
Другие вопросы по тегам:

Похожие вопросы: