1.装饰器
本质是函数,用def定义,用来装饰其他函数,为其他函数添加附加功能。
原则:1)不能修改被装饰的函数的源代码
2)不能修改被装饰的函数的调用方式
实现装饰器知识储备:
1)函数即“变量”,定义一个函数,就相当于把函数体赋值给了函数名,与变量的内存回收机制也一样
2)高阶函数:把函数作为参数传入
3)嵌套函数:在一个函数体内再定义一个函数
高阶函数+嵌套函数---->装饰器
示例:
1 # Author:Tang Ziyue 2 3 #用装饰器给test函数增加计算运行时间的功能 4 5 import time 6 7 def timer(func): 8 def deco(): 9 start_time = time.time() 10 func() #run test() 11 end_time = time.time() 12 print("the run time is %s"%(end_time-start_time)) 13 return deco 14 15 @timer #相当于test = timer(test),此时test为deco的内存地址,调用test相当于调用deco 16 def test(): 17 time.sleep(2) 18 print("in the test") 19 20 test() #run deco()
但是装饰器应该适用于所有函数,无参数的,一个参数的,两个参数的等等。
1 # Author:Tang Ziyue 2 3 #用装饰器给test函数增加计算运行时间的功能 4 5 import time 6 7 def timer(func): 8 def deco(*arg,**kwargs ): 9 start_time = time.time() 10 func(*arg,**kwargs) #run test() 11 end_time = time.time() 12 print("the run time is %s"%(end_time-start_time)) 13 return deco 14 15 @timer #相当于test = timer(test),此时test为deco的内存地址,调用test相当于调用deco 16 def test1(): 17 time.sleep(2) 18 print("test1") 19 20 @timer 21 def test2(name,age): 22 time.sleep(3) 23 print("test:",name,age) 24 25 test1() #run deco() 26 test2("tzy",23)
终极装饰器
1 # Author:Tang Ziyue 2 3 #给不同的网页函数增加验证用户名的功能,并且验证方式有多种 4 5 user,pwd = 'tzy','tangziyue' 6 7 def auth(auth_type): 8 print("auth func:",auth_type) 9 def out_wrapper(func): 10 def wrapper(*args,**kwargs): 11 print("wrapper func args:",*args,**kwargs) 12 if auth_type == "local": 13 username = input("Username:").strip() 14 password = input("Password:").strip() 15 if username == user and password == pwd: 16 print("\033[32;1mUser has passed authentication\033[0m") 17 res = func(*args,**kwargs) 18 return res#用来返回函数的返回值 19 else: 20 exit("\033[31;1mInvalid username or password\033[0m") 21 elif auth_type == "ldap": 22 print("不会ladap...") 23 return wrapper 24 return out_wrapper 25 26 27 def index(): 28 print("welcome to index page") 29 30 @auth(auth_type="local")#由于需要加参数,所以装饰器需要再加一层,home = out_wrapper(home) 31 def home(): 32 print("welcome to home page") 33 return "from home" 34 35 @auth(auth_type="ldap") 36 def bbs(): 37 print("welcome to bbs page") 38 39 index() 40 print(home()) 41 bbs()
2.迭代器&生成器
列表生成式:[i*2 for i in range(10)]
>>>[0,2,4,6,8,10,12,14,16,18]
生成器:只有在调用时才会生成相应的数据,只记录当前位置,只有一个next()方法
a = (i*2 for i in range(10))
---恢复内容结束---
1.装饰器
本质是函数,用def定义,用来装饰其他函数,为其他函数添加附加功能。
原则:1)不能修改被装饰的函数的源代码
2)不能修改被装饰的函数的调用方式
实现装饰器知识储备:
1)函数即“变量”,定义一个函数,就相当于把函数体赋值给了函数名,与变量的内存回收机制也一样
2)高阶函数:把函数作为参数传入
3)嵌套函数:在一个函数体内再定义一个函数
高阶函数+嵌套函数---->装饰器
示例:
1 # Author:Tang Ziyue 2 3 #用装饰器给test函数增加计算运行时间的功能 4 5 import time 6 7 def timer(func): 8 def deco(): 9 start_time = time.time() 10 func() #run test() 11 end_time = time.time() 12 print("the run time is %s"%(end_time-start_time)) 13 return deco 14 15 @timer #相当于test = timer(test),此时test为deco的内存地址,调用test相当于调用deco 16 def test(): 17 time.sleep(2) 18 print("in the test") 19 20 test() #run deco()
但是装饰器应该适用于所有函数,无参数的,一个参数的,两个参数的等等。
1 # Author:Tang Ziyue 2 3 #用装饰器给test函数增加计算运行时间的功能 4 5 import time 6 7 def timer(func): 8 def deco(*arg,**kwargs ): 9 start_time = time.time() 10 func(*arg,**kwargs) #run test() 11 end_time = time.time() 12 print("the run time is %s"%(end_time-start_time)) 13 return deco 14 15 @timer #相当于test = timer(test),此时test为deco的内存地址,调用test相当于调用deco 16 def test1(): 17 time.sleep(2) 18 print("test1") 19 20 @timer 21 def test2(name,age): 22 time.sleep(3) 23 print("test:",name,age) 24 25 test1() #run deco() 26 test2("tzy",23)
终极装饰器
1 # Author:Tang Ziyue 2 3 #给不同的网页函数增加验证用户名的功能,并且验证方式有多种 4 5 user,pwd = 'tzy','tangziyue' 6 7 def auth(auth_type): 8 print("auth func:",auth_type) 9 def out_wrapper(func): 10 def wrapper(*args,**kwargs): 11 print("wrapper func args:",*args,**kwargs) 12 if auth_type == "local": 13 username = input("Username:").strip() 14 password = input("Password:").strip() 15 if username == user and password == pwd: 16 print("\033[32;1mUser has passed authentication\033[0m") 17 res = func(*args,**kwargs) 18 return res#用来返回函数的返回值 19 else: 20 exit("\033[31;1mInvalid username or password\033[0m") 21 elif auth_type == "ldap": 22 print("不会ladap...") 23 return wrapper 24 return out_wrapper 25 26 27 def index(): 28 print("welcome to index page") 29 30 @auth(auth_type="local")#由于需要加参数,所以装饰器需要再加一层,home = out_wrapper(home) 31 def home(): 32 print("welcome to home page") 33 return "from home" 34 35 @auth(auth_type="ldap") 36 def bbs(): 37 print("welcome to bbs page") 38 39 index() 40 print(home()) 41 bbs()
2.迭代器&生成器
列表生成式:[i*2 for i in range(10)]
>>>[0,2,4,6,8,10,12,14,16,18]
生成器:只有在调用时才会生成相应的数据,只记录当前位置,只有一个next()方法
a = (i*2 for i in range(10))
迭代器:可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。
把list、dict、str等Iterable变成Iterator可以使用iter()函数:
>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter('abc'), Iterator)
True
range(10)和文件其实也是迭代器
3.内置函数
https://www.cnblogs.com/alex3714/articles/5740985.html
内置参数详解 https://docs.python.org/3/library/functions.html?highlight=built#ascii
4.Json与pickle序列化
序列化:将对象的状态信息转换为可以存储或传输的形式的过程。 在序列化期间,对象将其当前状态写入到临时或持久性存储区。 以后,可以通过从存储区中读取或反序列化对象 的状态,重新创建该对象。
Json只能处理字符串,列表,字典等简单的数据类型,Json是所有语言通用的,用于不同语言的数据交互。
# 序列化 json.dumps(info) #反序列化 json.loads(f.read())
复杂的用pickle,pickle可以处理所有的数据,但只有Python中有pickle。
序列化:
# Author:Tang Ziyue import pickle def sayhi(name): print("Hello1,",name) info = { 'name':'alex', 'age':22, 'func':sayhi } f = open("test.text",'wb') f.write(pickle.dumps(info))#这句话等价于pickle.dump(info,f) f.close()
反序列化:
# Author:Tang Ziyue import pickle # def sayhi(name): # print("Hello2,",name) f = open("test.text",'rb') data = pickle.loads(f.read())#等价于pickle.load(f) print(data["func"]("tzy"))
报错:AttributeError: Can't get attribute 'sayhi' on <module '__main__' from 'C:/Users/123/PycharmProjects/test/day4/反序列化.py'>
报错原因:序列化时随着程序执行结束函数内存地址被释放,反序列化时找不到sayhi。如果在反序列化时也定义一个sayhi函数,并且函数内容不同,结果为:
Hello2, tzy
None
说明"sayhi"保存的不是内存地址,而是整个数据对象。
5.软件目录结构规范
Foo/
|-- bin/
| |-- foo
|
|-- foo/
| |-- tests/
| | |-- __init__.py
| | |-- test_main.py
| |
| |-- __init__.py
| |-- main.py
|
|-- docs/
| |-- conf.py
| |-- abc.rst
|
|-- setup.py
|-- requirements.txt
|-- README
foo是执行程序,foo/下的main.py是程序的主入口,执行程序时需要执行foo,由foo调用main.py,这是跨目录的。
从一个目录程序找另一个目录中的程序的方法:
首先建文件目录如下
![]()
# Author:Tang Ziyue def login(): print("Welcome to my atm")
# Author:Tang Ziyue import os,sys print(__file__)#打印相对路径 print(os.path.abspath(__file__))#动态获取文件的绝对路径 print(os.path.dirname(os.path.abspath(__file__)))#获取上一级目录,到达bin;dirname返回目录名,不要文件名 #目的是找到conf目录下的main,所以得找到Atm,再向上一层 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR)#添加环境变量 from conf import settings from core import main main.login()

浙公网安备 33010602011771号