Accessing a decorator in a parent class from the child in Python

后端 未结 2 2018
日久生厌
日久生厌 2020-12-09 06:07

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

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

class baseclass(object):
             


        
2条回答
  •  一生所求
    2020-12-09 06:40

    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'
    

提交回复
热议问题