python之装饰器

高阶函数:

def func():
    print("This is func")


def foo(func):
    print("this is foo")
    func()
    return func


foo(func)    # 将函数 func 作为参数传递给 foo
print(foo(func))    # foo 的返回值是


执行结果:
this is foo
This is func
this is foo
This is func
<function func at 0x000001B6D6A02EA0>

 

匿名函数:

def foo():
    print("this is ", foo)


print(foo)    # 表示的是函数
foo()    # 执行foo函数

foo = lambda x : x * 2   # 匿名函数
print(foo("10"))    # 执行的是 lambda 表达式,而不是原来的 foo 函数,因为 foo 被重新定义了


执行结果:

<function foo at 0x000002D11FF4AB70>
this is foo
1010

 装饰器:

 1 import time
 2 
 3 username = "guoxf"
 4 password = "123456"
 5 
 6 def auth(a):
 7     print("ahth a:", a)
 8     def first(func):
 9         print("first func:", func)
10         def second(*args, **kwargs):
11             start_time = time.time()
12             print(*args, **kwargs)
13             user = input("Username:")
14             pwd = input("Password:")
15             if user == username and pwd == password:
16                 func(*args, **kwargs)
17                 stop_time = time.time()
18                 print("run time:%s" % (stop_time - start_time))
19             else:
20                 exit("输入错误,退出程序。。。")
21 
22         return second
23     print("this is first", first)
24 
25     return first
26 
27 
28 def test1():
29     print("welcome to chaina...")
30 
31 
32 # @auth("local")     
33 def test2(username, password):
34     time.sleep(1)
35     print("this is test2...")
36 
37 
38 @auth("authtication")
39 def test3():
40     time.sleep(1.5)
41     print("what are you doing...")
42 
43 
44 
45 first1 = auth("local")    # first1 指向 auth 函数的返回值first 的函数
46 test2=  first1(test2)    # test2 指向 first 函数的返回值second 的函数; test2 传给了 func
47 test2("guoxf","123456")    # 执行second 函数
48 
49 test3()

执行结果:

ahth a: authtication
this is first <function auth.<locals>.first at 0x000002093E80AF28>
first func: <function test3 at 0x000002093E82F048>
ahth a: local
this is first <function auth.<locals>.first at 0x000002093E80AF28>
first func: <function test2 at 0x000002093E80AEA0>
guoxf 123456
Username:guoxf
Password:123456
this is test2...
run time:140.81427788734436

Username:guoxf
Password:1234567
输入错误,退出程序。。。

 

下图中红框圈中的部分,两者结果相同

 

 

posted @ 2018-08-23 16:42  苟住,别浪  阅读(142)  评论(0编辑  收藏  举报