python之装饰器

从这里开始感觉到了难度。

加油。

装饰器:

 1 # Author:yebo
 2 
 3 def fib(max): #10
 4     n, a, b = 0, 0, 1
 5     while n < max:
 6         yield b   #把b返回到外面则yield b
 7         a, b = b, a + b
 8         n = n + 1
 9     return 0
10 
11 g = fib(10)
12 while True:
13     try:
14         x = next(g)   #也可以是: x = g.__next__()
15         print('g:', x)
16     except StopIteration as e:
17         print('Generator return value:', e.value)
18         break

升级版:(没有完全明白)

小插曲:在此期间遇到了pycharm可以run但无法进行debug的情况。百度多种方法无果。最后是删除了同目录下的.idea文件,问题才得以解决。

 1 __author__ = "Alex Li"
 2 import time
 3 user,passwd = 'alex','abc123'
 4 def auth(auth_type):
 5     print("auth func:",auth_type)
 6     def outer_wrapper(func):
 7         def wrapper(*args, **kwargs):
 8             print("wrapper func args:", *args, **kwargs)
 9             if auth_type == "local":
10                 username = input("Username:").strip()
11                 password = input("Password:").strip()
12                 if user == username and passwd == password:
13                     print("User has passed authentication")
14                     res = func(*args, **kwargs)  # from home
15                     print("---after authenticaion ")
16                     return res
17                 else:
18                     exit("1mInvalid username or password")
19             elif auth_type == "ldap":
20                 print("ldap type")
21 
22         return wrapper
23     return outer_wrapper
24 
25 def index():
26     print("welcome to index page")
27 
28 @auth(auth_type="local") # home = wrapper()
29 def home():
30     print("welcome to home  page")
31     return "from home"
32 
33 @auth(auth_type="ldap")
34 def bbs():
35     print("welcome to bbs  page")
36 
37 index()
38 print(home()) #wrapper()
39 bbs()

斐波那契数列:

 1 # Author:yebo
 2 
 3 
 4 """
 5 #小知识:
 6 a, b = b, a+b
 7 #该赋值语句相当于:
 8 t = (b, a+b)   #t是一个元组
 9 a = t[0]
10 b = t[1]
11 """
12 
13 def fib(max):
14     n, a, b = 0, 0, 1
15     while n < max:
16         yield b   #变成了一个生成器
17         a, b = b, a+b
18         n += 1
19     return 0
20 
21 max = int(input("how many fibnacci number do you want?"))
22 f = fib(max)
23 print(fib(max))
24 print(f.__next__())
25 print(f.__next__())
26 print(f.__next__())
27 print(f.__next__())
28 
29 print("---start loop---")
30 for i in f:
31     print(i)   #注意for循环的是i

 

posted @ 2018-08-16 22:23  松江小旋风  阅读(101)  评论(0)    收藏  举报