W4_python_decorator_generator_Iteratable_Iterator
- 50.第03章节-Python3.5-装饰器详解
- 51.第04章节-Python3.5-装饰器应用详解
- 52.第05章节-Python3.5-装饰器之函数即变量
- 53.第06章节-Python3.5-装饰器之高阶函数
- 54.第07章节-Python3.5-装饰器之嵌套函数
- 55.第08章节-Python3.5-装饰器之案例剖析1
- 56.第09章节-Python3.5-装饰器之案例剖析2
- 57.第10章节-Python3.5-装饰器之终极讲解
- 58.第11章节-Python3.5-迭代器与生成器1
- 59.第12章节-Python3.5-迭代器与生成器2
- 60.第13章节-Python3.5-迭代器与生成器并行
- 61.第14章节-Python3.5-内置方法详解1-2
- 63.第16章节-Python3.5-Json与pickle数据序列化
- 64.第17章节-Python3.5-软件目录结构规范
- 65.第18章节-w4-practices
- 获取文件所在路径,添加到sys.path
50.第03章节-Python3.5-装饰器详解
1.装修器定义:装饰器本质是函数,(装饰其它函数)就是为其它函数添加附件功能
2.原则:a)不能修改被装饰函数的源代码
b)不能修改被装饰函数的调用方式
51.第04章节-Python3.5-装饰器应用详解
52.第05章节-Python3.5-装饰器之函数即变量
53.第06章节-Python3.5-装饰器之高阶函数
高阶函数:
a)把一个函数名当作实参传给另一个函数(可以实现装修器中的:不能修改被装饰函数的源代码的情况下为函数增加功能)
def bar():
print("in the bar")
def test(func):
print(func)
func()
test(bar)
b)返回值中包含函数名(可以实现装修器中的:不修改函数的调用方式)
import time
def bar():
time.sleep(3)
print("in the bar")
def test(func):
print(func)
return func
# print(test(bar))
bar = test(bar)
bar() #run bar
54.第07章节-Python3.5-装饰器之嵌套函数
高阶函数 + 嵌套函数 => 装修器
x = 0
def gradpa():
x = 1
def dad():
x = 2
def son():
x = 3
print(x)
son()
dad()
gradpa()
55.第08章节-Python3.5-装饰器之案例剖析1
装饰器一:
import time
def timer(func):
def deco():
start_time = time.time()
func()
stop_time = time.time()
print("the func run time is :{runtime}".format(runtime = (stop_time - start_time)))
return deco
@timer
def test1():
time.sleep(2)
print("in the test1")
test1()
56.第09章节-Python3.5-装饰器之案例剖析2
装饰器二:解决参数传递问题
import time
def timer(func):
def deco(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
stop_time = time.time()
print("the func run time is :{runtime}".format(runtime = (stop_time - start_time)))
return deco
@timer
def test1():
time.sleep(2)
print("in the test1")
@timer
def test2(name,age):
time.sleep(2)
print("in the test2:",name,age)
test1()
test2("alex",age = 32)
57.第10章节-Python3.5-装饰器之终极讲解
user = "wu"
passwd = "pass"
def auth(func):
def wrapper(*args,**kwargs):
username = input("please input username:")
password = input("please input password:")
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = func(*args,**kwargs)
print("---after authentication---")
return res
else:
print("\033[31;1mInvalid username or password\033[0m")
return wrapper
def index():
print("welcome index page")
@auth
def home():
print("welcome home page")
def bbs():
print("welcome bbs page")
home()
ps:
1.理解参数传递过程
2.当层级较多时,可断点调试
#!/usr/bin/env python
# -*-coding:utf-8-*-
# author: Mr.Wu
user = "wu"
passwd = "pass"
def auth(auth_type):
def outer_wrapper(func):
def wrapper(*args, **kwargs):
if auth_type == "local":
username = input("please input username:")
password = input("please input password:")
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = func(*args, **kwargs)
print("---after authentication---")
return res
else:
print("\033[31;1mInvalid username or password\033[0m")
elif auth_type == "ldap":
print("ldap authenticatoin")
res = func(*args, **kwargs)
print("---after authentication---")
return res
return wrapper
return outer_wrapper
def index():
print("welcome index page")
@auth(auth_type="local")
def home():
print("welcome home page")
return "from home"
@auth(auth_type="ldap")
def bbs():
print("welcome bbs page")
home()
print(home())
bbs()
58.第11章节-Python3.5-迭代器与生成器1
生成器:只有在调用时才会生成相应的数据
生成器的优点:可以节省内存资源
比较列表与生成器:
a = [ i*2 for i in range(10000000) ]
b = ( i*2 for i in range(10000000) )
for n in b:
print(n)
b.next() #只有一个next方法,在python2中,为b.next()
#斐波拉契
# def fib(max):
# a,b,n = 0,1,0
# while n < max:
# a,b = b,a + b
# print(a)
# n = n + 1
# return "done"
#
# fib(10)
#转为生成器
def fib(max):
a,b,n = 0,1,0
while n < max:
a,b = b,a + b
yield a
n = n + 1
return "done"
f = fib(10)
print(f.__next__())
print("testxxx")
print(f.__next__())
print(f.__next__())
print("testxxx")
print(f.__next__())
59.第12章节-Python3.5-迭代器与生成器2
生成器案例:
import time
def consumer(name):
print("{name}准备吃包子了".format(name = name))
while True:
baozi = yield
print("包子{baozi}分给{name}吃了".format(baozi=baozi,name=name))
# c1 = consumer("user1")
# c1.__next__()
# c1.send("1")
# c1.send("2")
def producer(name):
c1 = consumer("c1")
c2 = consumer("c2")
c1.__next__()
c2.__next__()
print("开始做包子了")
baozi_no = 1
for i in range(10):
time.sleep(1)
print("{name}做了2个包子".format(name=name))
c1.send(baozi_no)
c2.send(baozi_no+1)
baozi_no = baozi_no + 2
producer("alex")
60.第13章节-Python3.5-迭代器与生成器并行
Iterable isinstance
可以直接作用于for循环的对象统称为可迭代对象:Iterable
from collections import Iterable
print(isinstance([],Iterable))
print(isinstance("",Iterable))
print(isinstance({},Iterable))
print(isinstance((),Iterable))
print(isinstance(100,Iterable))
Iterator
可以被next()函数调用并且不断返回下一个值的对象称为迭代器:Iterator
查看对像的方法:dir(对象)
使用
from collections import Iterator
print(isinstance((x for x in range(5)), Iterator))
iter()方法
iter()方法可以把可迭代对象转变为一个迭代器对象
a = iter(['a','b','c'])
print(a.next())
print(a.next())
61.第14章节-Python3.5-内置方法详解1-2
dir()
exec() #执行一段代码
eval() #将字典形式的字符串处理成字典类型
map()
globals() #获取当前文件中所有全局变量,注:不包括函数中的局部变量
hash()
bin()
oct()
hex()
sorted()
把字典按key排序打印
a = {6:2,8:0,1:4,-5:6,99:11,4:32}
print(a.items())
print(sorted(a.items()))
print(sorted(a.items(),key=lambda x:x[1]))
zip()
a = ['a','b','c','d']
b = [1,2,3,4,5]
for i in zip(a,b):
print(i)
locals()
63.第16章节-Python3.5-Json与pickle数据序列化
json dumps/dump
import json
data = {
"key1":"value",
"key2":[1,2,3]
}
with open("json_1.txt","w") as f:
f.write(json.dumps(data))
#等价于
import json
data = {
"key1":"value",
"key2":[1,2,3]
}
with open("json_1.txt","w") as f:
json.dump(data,f)
json loads/load
import json
with open("json_1.txt", "r") as f:
data = json.loads(f.read())
print(data)
# 等价于
import json
with open("json_1.txt", "r") as f:
data = json.load(f)
print(data)
json编码问题
import json
dic = (1:'中国',2:'b')
f = open('test_json.txt','w',encoding='utf-8')
json.dump(dic, f, ensure_ascii=False)
#json.dump(dic, f)
#感受下如何不加ensure_ascii=False后,文件内容的区别
f.close()
f = open('test_json.txt',encoding='utf-8')
res = json.load(f)
f.close()
print(type(res), res)
pickle dumps/dump
import pickle
def func_test(name):
print(name)
data = {
"pickle":"dump",
"func":func_test
}
# with open("pickle_1.txt","wb")as f:
# f.write(pickle.dumps(data))
#等价于
with open("pickle_1.txt","wb")as f:
pickle.dump(data,f)
pickle loads/load
import pickle
def func_test(name):
print("hello",name)
# with open("pickle_1.txt","rb")as f:
# print(pickle.loads(f.read())["func"]("test_name"))
#等价于
with open("pickle_1.txt","rb")as f:
print(pickle.load(f)["func"]("test_name"))
64.第17章节-Python3.5-软件目录结构规范
注意:项目首字母大写
Atm/
├── bin
│ ├── atm.py
│ └── __init__.py
├── conf
│ └── __init__.py
├── core
│ ├── __init__.py
│ └── main.py
├── docs
│ ├── abc.rst
│ └── conf.py
├── logs
│ └── __init__.py
├── README
├── requirements.txt
└── setup.py
目录间程序调用
假如从bin下的atm调用core下的main
main.py
print("welcome to atm")
import os, sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(BASE_DIR)
sys.path.append(BASE_DIR)
from core import main
main
65.第18章节-w4-practices
模拟实现一个ATM + 购物商城程序
额度 15000或自定义
实现购物商城,买东西加入 购物车,调用信用卡接口结账
可以提现,手续费5%每月22号出账单,每月10号为还款日,过期未还,按欠款总额 万分之5 每日计息
支持多账户登录
支持账户间转账
记录每月日常消费流水
提供还款接口
ATM记录操作日志
提供管理接口,包括添加账户、用户额度,冻结账户等。。。
用户认证用装饰器
示例代码 https://github.com/triaquae/py3_training/tree/master/atm
获取文件所在路径,添加到sys.path
from os import getcwd,path
from sys import path as sys_path
sys_path.insert(0,path.dirname(getcwd()))
python_控制台输出带颜色的文字方法:
https://www.cnblogs.com/Eva-J/p/8330517.html