1. 程式人生 > 其它 >一篇文章讓你完全明白到底什麼是BFC!

一篇文章讓你完全明白到底什麼是BFC!

被裝飾的函式,總是被替換成@符號所引用的函式的返回值。這是本質

因此,被裝飾的函式會變成什麼,完全取決於@符號所引用的函式的返回值

如果@符號所引用的函式,返回值是字串,那被裝飾的函式就被替換成了字串

如果@符號所引用的函式,返回值是函式,那被修飾的函式在替換之後還是函式

1.

def funA(fn):
    print('A')
    fn()
    return "fkit"

@funA
def funB():
    print("B")

print(funB)
A
B
fkit
#funA()執行完成後返回的是fkit,因此funB就不再是函式,而是被替換成了字串

2.@符號所引用的函式的返回值是還是函式

下面的程式定義 了一個裝飾器函式foo, 該函式執行完成後並不是返回普通值,而是返回bar函式(這是關鍵),這意味著被該@foo修飾的函式最終都會被替換成bar函式

def foo(fn):
    def bar(*args):
        print("===1===", args)
        n = args[0]
        print("===2===", n * (n-1))
        print(fn.__name__)
        fn(n*(n-1))
        print("*"*15)
        return fn(n*(n-1))
    
return bar @foo def my_test(a): print("==my_test function", a) print(my_test) my_test(10) print("=="*15) my_test(6,5)
<function foo.<locals>.bar at 0x00000217E0C6B1F0>
===1=== (10,)
===2=== 90
my_test
==my_test function 90
***************
==my_test function 90
==============================
===1=== (6, 5)
===2=== 30 my_test ==my_test function 30 *************** ==my_test function 30 請按任意鍵繼續. . .

例子:對函式進行引數檢查

def auth(fn):
    def auth_fn(*args):
        print("------模擬許可權檢查------")
        fn(*args)

    return auth_fn

@auth
def test(a,b):
    print("run test function , the args is %s, %s" %(a,b))

test(10,15)
------模擬許可權檢查------
run test function , the args is 10, 15
請按任意鍵繼續. . .