有没有办法在装饰函数中插入一些动作

时间:2016-05-14 06:55:31

标签: python decorator

我想在装饰函数中插入一些动作,但我不想触及该函数的代码。我可以在定义装饰器时插入动作吗?只添加不删除。

def real_decorator(func):
    def __decorator():
        print 'enter the func'
        func() # <- Can I insert some action inside this from here?
        print 'exit the func'
    return __decorator  


@real_decorator
def decorated_function():
    print "I am decorated"


decorated_function()

1 个答案:

答案 0 :(得分:1)

这是怎么回事?

def real_decorator(func):

    def __decorator():
        print 'enter the func'
        for action in __decorator.extra_actions:
            action()
        func()
        print 'exit the func'

    __decorator.extra_actions = []

    return __decorator

@real_decorator
def decorated_function():
    print "I am decorated"

decorated_function()

def new_action():
    print "New action"

decorated_function.extra_actions.append(new_action)

decorated_function()