@zhangyy
2021-08-15T14:02:40.000000Z
字数 1931
阅读 120
Python学习
一: 迭代器&生成器
二: 装饰器
三: Json & pickle 数据序列化
四:软件目录结构规范
装饰器:本质就是函数,(装饰其它函数的)就是为其他函数添加附加功能
原则:1 不能修改稿被装饰的函数的源代码
2 不能修改被装饰的函数的调用方式
实现装饰器的知识储备:
1. 函数就是“变量”
2. 高洁函数
a: 把一个函数名当做做实参传给另外一个函数 (不修改被装饰函数源代码的下为其添加功能)
b:返回值中包含函数名 (不修改函数的调用方式)
3.嵌套函数
高阶函数+嵌套函数==》装饰器
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:zhangyy
import time
def timer(fanc):
def warpper(*args,**kwargs):
start_time=time.time()
fanc()
stop_time=time.time()
print("int fanc run time is %s" %(stop_time-start_time))
return warpper
@timer
def test1():
time.sleep(3)
print("in the test1")
@timer
def test2():
time.sleep(3)
print("in the test2")
test1()
test2()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:zhangyy
import time
def timer(fanc):
def warpper(*args,**kwargs):
start_time=time.time()
fanc(*args,**kwargs)
stop_time=time.time()
print("int fanc run time is %s" %(stop_time-start_time))
return warpper
@timer
def test1():
time.sleep(3)
print("in the test1")
@timer
def test2(name,age):
time.sleep(3)
print("in the test2",name
,age)
test1()
test2("zhangyy",26)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:zhangyy
import time
user,passwd = 'zhangyy','abc123'
def auth(auth_type):
print("auth func:",auth_type)
def outer_wrapper(func):
def wrapper(*args, **kwargs):
print("wrapper func args:", *args, **kwargs)
if auth_type == "local":
username = input("Username:").strip()
password = input("Password:").strip()
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = func(*args, **kwargs) # from home
print("---after authenticaion ")
return res
else:
exit("\033[31;1mInvalid username or password\033[0m")
elif auth_type == "ldap":
print("搞毛线ldap,不会。。。。")
return wrapper
return outer_wrapper
def index():
print("welcome to index page")
@auth(auth_type="local") # home = wrapper()
def home():
print("welcome to home page")
return "from home"
@auth(auth_type="ldap")
def bbs():
print("welcome to bbs page")
index()
print(home()) #wrapper()
bbs()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:zhangyy
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'
fib(10)