Python中的装饰器用法详解

2019-10-05 10:10:24于丽

    # 我们定义另外一个函数
    def shout(word="yes") :
        return word.capitalize()+" !"
 
    def whisper(word="yes") :
        return word.lower()+"...";
 
    # 然后我们返回其中一个
    if type == "shout" :
        # 我们没有使用(),因为我们不是在调用该函数
        # 我们是在返回该函数
        return shout
    else :
        return whisper
 
# 然后怎么使用呢 ?
 
# 把该函数赋予某个变量
talk = getTalk()    
 
# 这里你可以看到talk其实是一个函数对象:
print talk
#输出 : <function shout at 0xb7ea817c>
 
# 该对象由函数返回的其中一个对象:
print talk()
 
# 或者你可以直接如下调用 :
print getTalk("whisper")()
#输出 : yes...
还有,既然可以返回一个函数,我们可以把它作为参数传递给函数:
def doSomethingBefore(func) :
    print "I do something before then I call the function you gave me"
    print func()
 
doSomethingBefore(scream)
#输出 :
#I do something before then I call the function you gave me
#Yes !
这里你已经足够能理解装饰器了,其他它可被视为封装器。也就是说,它能够让你在装饰前后执行代码而无须改变函数本身内容。

手工装饰

那么如何进行手动装饰呢?
# 装饰器是一个函数,而其参数为另外一个函数
def my_shiny_new_decorator(a_function_to_decorate) :
 
    # 在内部定义了另外一个函数:一个封装器。
    # 这个函数将原始函数进行封装,所以你可以在它之前或者之后执行一些代码
    def the_wrapper_around_the_original_function() :
 
        # 放一些你希望在真正函数执行前的一些代码
        print "Before the function runs"
 
        # 执行原始函数
        a_function_to_decorate()
 
        # 放一些你希望在原始函数执行后的一些代码
        print "After the function runs"
 
    #在此刻,"a_function_to_decrorate"还没有被执行,我们返回了创建的封装函数