Python 装饰器简单示例

2023-01-31 01:01:04 示例 简单 装饰

简单装饰器示例:

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

相关文章