1. 程式人生 > >Python 裝飾器簡單示例

Python 裝飾器簡單示例

裝飾器

簡單裝飾器示例:

def servlet(func):
    print("into servlet")#1
    print(servlet)#2
    def foo():
        print("into foo")#7
        print(func)#8,真正的bar函數
        func()#9
        print("out foo")#13
    print(foo)#3
    print("out servlet")#4
    return foo
@servlet
def bar():
    print("in old bar")/#0
    print(bar)#11
    print("out old bar")#12
print(bar)#5,已經被裝飾器裝飾了
bar()#6

執行順序如上,執行結果如下

into servlet
<function servlet at 0x00000186A1341E18>
<function servlet.<locals>.foo at 0x00000186A1801E18>
out servlet
<function servlet.<locals>.foo at 0x00000186A1801E18>
into foo
<function bar at 0x00000186A1801AE8>
in old bar
<function servlet.<locals>.foo at 0x00000186A1801E18>
out old bar
out foo

Process finished with exit code 0

可變參數裝飾器示例:

def desc(func):
    print("in desc")
    print(desc)
    def foo(*arg1,**arg2):
        print("in foo")
        print(func)
        x = func(*arg1,**arg2)
        print("out foo")
        return x
    print(foo)
    print("out desc")
    return foo
@desc
def setArg1(x,y):
    print("in setArg1")
    print(setArg1)
    print("out setArg1")
    return x + y
@desc
def setArg2(x,y,z):
    print("in setArg2")
    print(setArg2)
    print("out setArg2")
    return x + y + z
print(setArg1)
print(setArg2)
x = setArg1(100,200)
y = setArg2(100,200,300)
print(x)
print(y)

代碼如上,執行結果如下

in desc
<function desc at 0x0000024DF2611E18>
<function desc.<locals>.foo at 0x0000024DF2AD1E18>
out desc
in desc
<function desc at 0x0000024DF2611E18>
<function desc.<locals>.foo at 0x0000024DF2AD1EA0>
out desc
<function desc.<locals>.foo at 0x0000024DF2AD1E18>
<function desc.<locals>.foo at 0x0000024DF2AD1EA0>
in foo
<function setArg1 at 0x0000024DF2AD1AE8>
in setArg1
<function desc.<locals>.foo at 0x0000024DF2AD1E18>
out setArg1
out foo
in foo
<function setArg2 at 0x0000024DF2AD1A60>
in setArg2
<function desc.<locals>.foo at 0x0000024DF2AD1EA0>
out setArg2
out foo
300
600

Process finished with exit code 0

Python 裝飾器簡單示例