第四课学习的主要内容有内置函数,生成器,迭代器,pyton装饰器,python开发规范,Json & pickle 序列化与反序列化
内置函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 str_1 = "123" 2 no_1= 456 3 #绝对值 4 i = abs(no_1) 5 print(i) 6 #循环参数,如果每个元素都为真,则返回为True,否则返回False 7 i =all([True,True,False]) 8 print(i) 9 10 #假值:0,None,"",[],(),{} 11 12 13 #其中只要有1个为真,返回就为真 14 any(["1",None,[],123]) 15 #ascii(),对象的类型找到__repr__,获取其返回值 16 li = list([11,22,33]) 17 print(ascii(li)) 18 19 #bin()#二进制 20 r = bin(2) 21 print(r) 22 #oct()#八进制 23 r = oct(8) 24 print(r) 25 #int()#十进制 26 r = int(4) 27 print(r) 28 #hex()#十六进制 29 r = hex(10) 30 s = hex(15) 31 print(r) 32 print(s) 33 34 # 十进制转换为其他进制 35 i = int('0b010101',base=2) 36 print(i) 37 i1 = int('11',base=8) 38 print(i1) 39 i2 = int('0xe',base=16) 40 print(i2) 41 42 #bool,判断真假 None,[],{},"", 43 44 45 #bytes 字节 46 #bytearray 字节列表[字节] 47 48 #字节,字符串 49 b1 =bytes("abc",encoding='utf-8') 50 print(b1) 51 b2 = str(b1,encoding='utf-8') 52 print(b2) 53 54 #chr 数字转为为字符 55 #ord 字符转为数字 只是适用ascii 56 57 print(chr(65)) 58 print(ord('z')) 59 60 #随机验证码 61 62 import random 63 temp = "" 64 65 for i in range(6): 66 num = random.randrange(0,4) 67 if num == 1 or num == 3: 68 num1 = random.randrange(0,10) 69 num1 = str(num1) 70 temp = temp + num1 71 else: 72 num2 = random.randrange(65,91) 73 num2 = chr(num2) 74 temp = temp + num2 75 76 print(temp) 77 78 79 #callable ,对象是否是可执行的 80 81 f1 = 123 82 print(callable(f1)) 83 84 classmethod() 85 86 #compile 编译 把字符串编译成 python 可执行的代码 87 88 #dir 89 90 li = [] 91 print(dir(li)) 92 93 help(list) 94 95 #divmod(),除法,商多少余多少10/3 ,(3,1) 商3余1 ,可以在分页时使用 96 97 yeMian = divmod(10001,20) 98 print(yeMian) 99 100 101 for i in enumerate("abcd",1): 102 print(i) 103 104 105 # evel 可以执行一个字符串形式的表达式,例如 "a+b*c*(1+34+4)" 106 107 a = "10+2+3*4-5+6/8" 108 print(eval(a)) 109 110 print(eval("a + +b +20", {"a": 99, "b": 1})) 111 112 exec("for i in range(10):print(i)") 113 # compile 编译代码 114 # evel,表达式,有返回值 115 # exec,执行pytho代码,无返回值 116 117 118 # filte 循环可迭代的对象,获取每一个参数,函数(参数) 119 def f1(args): 120 if args > 22: 121 return args 122 res = filter(f1,[11,22,33,44]) 123 res = filter(lambda x: x > 22,[11,22,33,44]) 124 125 for i in res: 126 print(i) 127 128 # map(函数,可迭代的对象),map将传入的函数依次作用到序列中的每个元素,并把结果作为一个新的列表返回 129 130 def f1(args): 131 return args + 100 132 133 res = map(f1,[1,2,3,4]) 134 for i in res: 135 print(i) 136 137 #max,最大值 138 #min,最小值 139 140 l1 = [11,22,33,44,55,] 141 t1 = (66,77,88) 142 res = max(l1) 143 res1 = min(l1) 144 print(res,res1) 145 #pow(),指数运算 146 147 #reversed(列表,元组) 翻转 148 print(pow(2,10)) 149 c =reversed(t1) 150 for i in c: 151 print(i) 152 #round()四舍五入 153 print(round(3.5)) 154 #__import__(),导入模块取别名 155 import random 156 c =__import__('random') 157 print(c.randrange(1,10)) 158 #zip() 两个列表的元素合并 159 160 li = [11,22,33,44] 161 li2 =["22","33","44","55"] 162 d=zip(li,li2) 163 for i in d: 164 print(i)
生成器
列表生成式
>>> b = [i+1 for i in range(0,10)] >>> b [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
生成器(Generator)
生成器的一种简单写法,把上面的列表生成式的[],换成()就成了生成器了,python3.0中通过__next__调用
>>> b = (i+1 for i in range(10)) >>> b <generator object <genexpr> at 0x0000000003088518> >>> b.__next__() 1>>> b.__next__() 2 >>> b.__next__() 3 >>> b.__next__() 4 >>> b.__next__() 5 >>> b.__next__() 6 >>> b.__next__() 7 >>> b.__next__() 8 >>> b.__next__() 9 >>> b.__next__() 10 >>> b.__next__() Traceback (most recent call last): #当调用生成器数据超出范围时,解释器会抛出异常,可以通过异常处理来解决 File "<pyshell#39>", line 1, in <module> b.__next__() StopIteration
>>> b = (i+1 for i in range(10)) >>> while True: try: a=b.__next__() print(a) except StopIteration as e: print("end") break 1 2 3 4 5 6 7 8 9 10 end
用一个函数来实现斐波那契数列(Fibonacci),如:1, 1, 2, 3, 5, 8, 13, 21, 34, ... ,除第一个和第二个数外,任意一个数都等于前两个数相加的和。
1 >>> def fib(max): 2 a=0 3 b=1 4 n = 0 5 while n < max: 6 print(b) 7 a,b = b,a + b #该行等于 t = (b,a+b) ,t[0] = b ,t[1]=a+b 8 n += 1 9 return "done" 10 11 >>> f=fib(10) 12 1 13 1 14 2 15 3 16 5 17 8 18 13 19 21 20 34 21 55 22 >>> print(f) 23 done
把上面实现斐波那契数列的函数中的print(b) 改为 yield b 就成了生成器
>>> def fib(max): a=0 b=1 n = 0 while n < max: yield b a,b = b,a + b n += 1 return "done" >>> fib(10) <generator object fib at 0x00000000030AACA8>
上面生成器执行过程与函数过程有所不同,函数执行到return返回,生成器在执行过程中遇到yield 就返回停止执行,当下次再次执行,程序从yield 的位置继续执行
通过yield实现单线程下的并行计算效果
import time #消费者 def consumer(name): print("%s准备好吃包子了"%name) while True: baozi = yield print("%s吃%s个包子."%(name,baozi)) #生产者 def producer(name): a = consumer("A") b = consumer("B") a.__next__() #初始化 b.__next__() #初始化 print("%s要开始做包子了:"%name) for i in range(1,10): #做包子 time.sleep(1) a.send(i) #做一个包子发送给a,yield = 1,继续执行, b.send(i) #做一个包子发送给b,并执行 producer("zhangsan")
迭代器
for
循环的数据类型:
一类是集合数据类型,如list
、tuple
、dict
、set
、str
等;
一类是generator
,包括生成器和带yield
的generator function。
- 可迭代(Iterable):可以直接作用于
for
循环的对象。 - 迭代器(Iterator):可以被
next()
函数调用并不断返回下一个值的对象。
可以使用isinstance方法Iterable和Iterator
#判断是否是可迭代对象
>>> from collections import Iterable>>> isinstance([],Iterable) True >>> isinstance({},Iterable) True>>> isinstance((x for i in range(10)),Iterable) True #判断是否是迭代器 >>> from collections import Iterator >>> isinstance([],Iterator) False >>> isinstance({},Iterator) False >>> isinstance((x for i in range(10)),Iterator) True
可迭代对象可以通过iter()变成迭代器
>>> isinstance(iter([1,2,3,4]),Iterator)
True
装饰器
定义:本质是函数,就是为了其他函数添加附加的功能(装饰其他函数)。
原则:
- 不能修改被装饰的函数的源代码
- 不能修改被装饰的函数的调用方式
实现装饰器需要掌握的知识
- 函数即“变量”
- 高级函数
a:把一个函数名当做实参传给另外一个函数(在不修改被装饰函数源代码情况下为其添加功能)
b:返回值包含函数名(不修改函数的调用方式)
3.嵌套函数
装饰器= 高阶函数+嵌套函数
装饰器普通版
import time #装饰器 def timer(func): #timer(test1) func =test1 def deco(): start_time = time.time() func() stop_time = time.time() print("func run time is",stop_time - start_time) return deco #返回deco 内存地址 @timer #test1 = timer(test1) def test1(): time.sleep(2) print("in the test1") @timer def test2(): time.sleep(3) print("in the test2") test1() test2()
装饰器高潮版
user,passwd = "zhangxin","abc123" def auth(auth_type): print(auth_type) def wrapper_auther(func): def wrapper(*args, **kwargs): if auth_type == "local": username = input("Please input username:").strip() password = input("Please input password:").strip() if user == username and passwd == password: print("Login successful") func(*args, **kwargs) return func else: print("Account or password error") elif auth_type == "ldap": print("不会ldap") return wrapper return wrapper_auther # def index(): print("Welcome to index") @auth(auth_type = "local") #装饰器加参数 def home(): print("Welcome to home") return "from home" @auth(auth_type = "ldap") def setting(): print("Welcome to setting") index() print(home()) setting()
装饰器的练习
1 def feb(deep, a1, a2): 2 if deep == 10: 3 return a1 4 f = a1 + a2 5 res = feb(deep + 1, a2, f) 6 return res 7 8 9 s = feb(1, 0, 1) 10 print(s)
输出结果:
inner_前
index
inner_后
('return_index', 3, 4)
json序列化与反序列化
json序列化
1 import json 2 3 data = { 4 "name":"zhangsan", 5 "age": 28, 6 "city":"beijing" 7 } 8 f = open("json file1","w",encoding="utf-8") 9 #f.write(json.dumps(data))#序列化 10 json.dump(data,f) #json.dump(data,f) ==json.dump(data,f) 11 f.close()
json反序列化
import json f = open("json file1","r",encoding="utf-8") #data = json.loads(f.read()) #反序列化 data = json.load(f) # json.loads(f.read()) == json.load(f) print(data) f.close()
python开发目录规范
目录结构
Foo/
|-- bin/
| |-- foo
|
|-- foo/
| |-- tests/
| | |-- __init__.py
| | |-- test_main.py
| |
| |-- __init__.py
| |-- main.py
|
|-- docs/
| |-- conf.py
| |-- abc.rst
|
|-- setup.py
|-- requirements.txt
|-- README
解释:
bin/
: 存放项目的一些可执行文件,当然你可以起名script/
之类的也行。foo/
: 存放项目的所有源代码。(1) 源代码中的所有模块、包都应该放在此目录。不要置于顶层目录。(2) 其子目录tests/
存放单元测试代码; (3) 程序的入口最好命名为main.py
。docs/
: 存放一些文档。setup.py
: 安装、部署、打包的脚本。requirements.txt
: 存放软件依赖的外部Python包列表。README
: 项目说明文件。
作业
ATM作业需求
- 额度 15000或自定义
- 实现购物商城,买东西加入 购物车,调用信用卡接口结账
- 可以提现,手续费5%
- 每月22号出账单,每月10号为还款日,过期未还,按欠款总额 万分之5 每日计息
- 支持多账户登录
- 支持账户间转账
- 记录每月日常消费流水
- 提供还款接口
- ATM记录操作日志
- 提供管理接口,包括添加账户、用户额度,冻结账户等。。。
- 用户认证用装饰器