Five, Python 7 of object-oriented, decorative application function

7, function decorators application

Description :

  • After using the @ symbol references an existing function that can be used to modify other functions.
  • Essence @classmethod (class methods) and @staticmethod (static methods) as a function of decorator
  • Decorator function must be defined a parameter
# 装饰器函数
def foo(fn):          
    print('foo函数')
    print('----在目标表函数之前增加的活动----')
    fn()
    print('----在目标表函数之后增加的活动----')
    return 'python'

# 被装饰的函数
@foo
def bar():
    print('bar函数')

print(bar, type(bar))
foo函数
----在目标表函数之前增加的活动----
bar函数
----在目标表函数之后增加的活动----
python <class 'str'>

Analysis : The essence of function decorators

  1. Function to be decorated (bar) as an argument to a function of decorator (foo)

  2. The decorative function (bar) will be replaced with a function of decorator (foo) return value

Here, bar corresponds to 'python', as a string. When decorative function requires parameters passed if they are, the bar does not achieve the above parameter transfer function

Common usage :

# 装饰器函数
def foo(fn):     # 此处 fn 代表了被装饰的函数
    print('foo函数')
    
    def noname(*args):
        print('----在目标表函数之前增加的活动----')
        fn(*args)
        print('----在目标表函数之后增加的活动---')
        return 'python'
    
    return noname

# 被装饰的函数
@foo
def test(a, b):
    print('test函数')   
    print('参数a:', a)
    print('参数b:', b)
    
print(test(2, 4))
foo函数
----在目标表函数之前增加的活动----
test函数
参数a: 2
参数b: 4
----在目标表函数之后增加的活动---
python

Guess you like

Origin blog.csdn.net/qq_36512295/article/details/94547954