python 關於@的解釋

自從開始學習python,看源碼的時候經常可以看到@來修飾的方法,之前一直沒搞清楚。現在彙總下自己對於@的理解:

@是python的修飾符,Decorator類類似於C的預編譯宏,因此在代碼函數調用之前或者執行main函數之前就已經完成了編譯。

我可以創建修飾類或者是修飾方法,用來修飾方法。在寫一個修飾類的時候,必須要實現它的__CALL__方法。

1.修飾類(編譯過程)

class decorator(object):
    def __init__(self,f):
        print "inside decorator.__init__"
        f()
    def __call__(self):
        print "inside decorator.__call__"

@decorator
def aFunction():
    print "inside aFunction()"

print "Finished decorating aFunction()"
aFunction()
輸出結果:

inside decorator.__init__
inside aFunction()
Finished decorating aFunction()
inside decorator.__call__
這個是一個修飾類,我們可以看到它的編譯過程,在調用之前就已經編譯完成

2.修飾方法(其中可以理解參數的傳遞)

def decorator_maker_with_arguments(decorator_arg1, decorator_arg2):

    print "I make decorators! And I accept arguments:", decorator_arg1, decorator_arg2

    def my_decorator(func):
        # The ability to pass arguments here is a gift from closures.
        # If you are not comfortable with closures, you can assume it's ok,
        # or read: http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
        print "I am the decorator. Somehow you passed me arguments:", decorator_arg1, decorator_arg2

        # Don't confuse decorator arguments and function arguments!
        def wrapped(function_arg1, function_arg2) :
            print ("I am the wrapper around the decorated function.\n"
                  "I can access all the variables\n"
                  "\t- from the decorator: {0} {1}\n"
                  "\t- from the function call: {2} {3}\n"
                  "Then I can pass them to the decorated function"
                  .format(decorator_arg1, decorator_arg2,
                          function_arg1, function_arg2))
            return func(function_arg1, function_arg2)

        return wrapped

    return my_decorator

@decorator_maker_with_arguments("Leonard", "Sheldon")
def decorated_function_with_arguments(function_arg1, function_arg2):
    print ("I am the decorated function and only knows about my arguments: {0}"
           " {1}".format(function_arg1, function_arg2))

decorated_function_with_arguments("Rajesh", "Howard")
輸出結果:

I make decorators! And I accept arguments: Leonard Sheldon
I am the decorator. Somehow you passed me arguments: Leonard Sheldon
I am the wrapper around the decorated function.
I can access all the variables
	- from the decorator: Leonard Sheldon
	- from the function call: Rajesh Howard
Then I can pass them to the decorated function
I am the decorated function and only knows about my arguments: Rajesh Howard

由此2種方式應該可以完全理解了~



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章