一 装饰器
定义:本质是函数,作用是给其他函数增加附加功能
原则:1不能修改被装饰函数的源代码
2不能改变被装饰函数的调用方法
装饰器知识储备
1函数即“变量”
定义函数和定义变量的方式是类似的,定义变量是让变量名去引用给定的变量值,定义函数是让函数名去引用给定的函数体。
2高阶函数
2.1将函数作为实参传递给另一个函数,作用就是在不改变被传递函数的源代码的情况下给它增加功能
2.2返回值中包含被传递函数的函数名,作用就是可以不改变被传递函数的调用方式的情况下给它增加功能
3嵌套函数
在函数中用def在定义别的函数
装饰器编写方式
高阶函数(2种用法同时使用)+嵌套函数=装饰器
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author:liufeng
user,passwd ="alex","abc123"
def auth(auth_type):
def outwrapper(func):
def wrapper(*args,**kwargs):
if auth_type == "local":
username =input("username:").strip()
password =input("password:").strip()
if username ==user and password ==passwd:
print("\033[32;1mUser has passed auth\033[0m")
return func(*args,**kwargs)
else:
exit("Inavild username or password")
elif auth_type == "ldap":
print("it is ldap")
return wrapper
return outwrapper
def index():
print("welcome to index")
@auth(auth_type="local")
def home():
print("welcome to home")
@auth(auth_type="ldap") 返回wrapper函数的内存地址
def bbs():
print("welcome to bbs")
index()
home() 执行wrapper函数
bbs()
二 生成器
列表生成式
[ i*2 for i in range(10) ]
生成器
( i*2 for i in range(10) )
def fib(max):
n,a,b =0,0,1
while n < max:
yield b
a,b =b,a+b
n = n+1
return "done"
f =fib(100)
while True:
try:
x =next(f)
print(x)
except StopIteration as e:
print("Gen return value:",e.value)
break
import time
def consumer(name):
print("%s eat baozi"%name)
while True:
baozi =yield
print("baozi[%s],[%s]eat"%(baozi,name))
def productor(name):
c =consumer('A')
c2 =consumer('B')
c.__next__()
c2.__next__()
print("begin to make baozi")
for i in range(10):
time.sleep(1)
print("baozi is ok")
c.send(i)
c2.send(i)
consumer("liufeng")
productor("guoyutao")
生成器只能只用__next__方法取值或用循环去迭代取值,并且只能从前往后一个个取值,只保留当前取出的值。在函数中使用yield代替print输出值就可以将该函数变成生成器,生成器的作用是实现单线程下的并发运算即协程
三 迭代器
from collections import Iterable
'''判断数据对象是否为迭代器对象'''
print(isinstance([],Iterable))
list =[2,5,8,12]
'''将列表转化成迭代器'''
a =iter(list)
'''从迭代器中取值'''
print(a.__next__())
四 匿名函数
(lambda n:print(n))(5)
calc = lambda n:print(n)
calc(5)
这两段代码的作用是定义变量n,输出n的值
五 内置函数
abs() 求绝对值
all([0,1,2,-1]) 方法内的可迭代对象中所有元素都为真或者为空时返回True,否者返回False
any() 方法内的可迭代对象中任意元素为真时返回True,为空时或者元素都为假时返回False
ascii()
bin() 将十进制转换成二进制
bool() 判断真假
bytearray() 可修改的二进制
bytes() 不可修改的二进制
callable() 判断对象是否可调用
chr() 输入一个数字返回对应的ASCII的值
classmethod() 返回一个类的方法
compile() 编译代码
complex()
delattr()
dict()
dir() 查询对象具有哪些方法
divmod() 返回两个数相除的商和余数
enumerate()
eval() 将字符串形式的列表、字典等转换成列表、字典类型或者字符串形式的运算式计算出来 eval("[1,2,3]") eval("1 + 2")
exec() 将字符串形式的代码执行出结果 exec("for i in range(10):print(i)")
filter() filter(lambda n:n>5,range(10))
float()
format()
frozenset() 不可变的集合
getattr()
globals() 返回整个代码中变量和变量值的字典形式(只包含全局的)
hasattr()
hash() 返回一个哈希值
help()
hex() 将十进制转换成十六进制
id()
input()
int()
isinstance()
issubclass()
iter()
len()
list()
locals() 将代码中的全部局部变量输出
map() map(lambda n:n*n,range(10))
max()
memoryview()
min()
next()
object()
oct() 将十进制转换成八进制
open()
ord() 输入字符返回对应的ASCII编号
pow() pow(2,3)返回2的三次方
print()
property()
range()
repr()
reversed()
round() round(1.3333,2)保留小数点后多少位
set()
setattr()
slice()
sorted() 将字典排序 a={1:3,4:2,7:2,2:3}sorted(a.items(),key=lambda x:x[1])
staticme()
str()
sum()
super()
tuple()
type()
vars() 返回对象的所有属性名
zip() 将两组数据一一对应的输出 a=[1,2,3] b=["a","b","c"] zip(a,b)
__import__() 导入模块时模块名以字符串形式表示
六 json序列化
import json
json.dumps() 序列化,将字典转换成字符串
json.loads() 反序列化,将字符串转换成字典
import pickle
pickle.dumps() 序列化,将字典转换成字符串
pickle.loads() 反序列化,将字符串转换成字典
pip install -r requirement.txt 将软件依赖包自动安装
七 不同目录见文件调用
import os,sys
BASE_DIR =os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 获取程序最高一级的目录的路径
sys.path.append(BASE_DIR) 将获取的路径添加到python环境变量