标签:对象 for fun 方式 round 反序列化 字符 序列化 保留
装饰器
装饰器: 本质是函数(装饰函数),就是为其他函数添加附加功能
	原则:1. 不能修改被装饰器的函数的源代码与调用方式
	知识储备:
	1. 函数即"变量"
	2. 高阶函数
		a. 把一个函数名当实参传给另一个函数
		b. 返回值中包含函数名
	3. 嵌套函数
	
生成器
特点:
	1. 只有调用时才会生成相应的数据
	2. 只记录当前位置
	3. 只有一个__next__()方法
	( i*i for i in range(10) )
	
迭代器
	迭代对象: 可直接作用于for循环的对象统称为可迭代对象:Iterable
可以被next()调用并不断返回下一个值的对象称为迭代器:Iterator
迭代器一定是迭代对象,迭代对象不一定是迭代器
迭代对象可以通过iter()转变为迭代器
In[2]: from collections import Iterable
In[3]: isinstance([],Iterable)
Out[3]: True
In[4]: from collections import Iterator
In[5]: isinstance([],Iterator)
Out[5]: False
In[6]: a = [1, 2, 3, 4]
In[7]: isinstance(a, Iterator)
Out[7]: False
In[8]: b = iter(a)
In[9]: isinstance(b, Iterator)
Out[9]: True
内置方法:
In[2]: bin(255)   ----》 数字转为二进制
Out[2]: ‘0b11111111‘
In[4]: ascii([1,2,3])   ----》列表转字符串
Out[4]: ‘[1, 2, 3]‘
a = bytes("abcde",encoding="utf-8")
print(a)
b = bytearray("abcde",encoding="utf-8")  ---> 使字符变成列表可更改
print(b[1])
b[1] = 100
print(b)
>>> b‘abcde‘
>>> 98
>>> bytearray(b‘adcde‘)
>>> chr(98)  ----> 数字转ascii码
"b"
>>> ord("B")   ----》 ascii码转数字
66
		
code = "(1 + 2) * 5"
c = compile(code, "err.log",‘eval‘)  ---》 可执行的字符串代码转为可执行
print(c)
print(eval(c))
##################
<code object <module> at 0x00000260661F3ED0, file "", line 1>
15
#################
In[10]: divmod(5,2)   ----》 两数相除,返回商和余数
Out[10]: (2, 1)
eval() 、exec() ----> 字符串转为可执行方法
匿名函数
calc = lambda n:print(n)
calc(5)
---> 5
calc = lambda n:3 if n<4 else n
filter() ---> 过滤
res = filter(lambda n:n>5, range(10))
for i in res:
    print(i)
map() ----> 对传入的每个值进行处理
res = map(lambda n: n*n, range(10))  
---》[i*2 for i in range(10)]
---》[lambda i:i*2 for i in range(10)]
for i in res:
    print(i)
	
import functools
res = functools.reduce(lambda x,y: x+y, range(10))
print(res)
frozenset([1,2,3,4,5]) ---> 冻结集合,不可改
gloabs() ---> 打印全局变量
locals()  ---> 打印局部变量
hex() ---> 16进制
oct()  ----> 8进制
pow(3,5)  ----> 3**5
round(1.345,2) ---> 保留2位小数
a = {6: 2,8: 0,1: 4, -5: 6}
print(sorted(a.items()))  ----》 按key排序
---》 [(-5, 6), (1, 4), (6, 2), (8, 0)]
print(sorted(a.items(),key=lambda x:x[1]))  ---》 按value排序
---》 [(8, 0), (6, 2), (1, 4), (-5, 6)]
json不能将函数序列化
json序列化: json.dumps(info) 写入文件
json反序列化: json.loads(f.read()) 读出文件
pickle与json用法相同,能处理共复杂的(函数等。。)
pickle 只能在python中用,json能在java中使用
pickle.dump(info,f)  == f.write(pickle.dumps(info))
pickle.load(f)  == pickle.loads(f.read())
os.path.abspath(__file__)  返回绝对路径
os.path.dirname()   返回目录
sys.path.append() 添加环境路径
知识补充:
if [True for line in context if name in line]:
	  print("ok")
查name是否在line中
标签:对象 for fun 方式 round 反序列化 字符 序列化 保留
原文地址:http://www.cnblogs.com/sshcy/p/8016387.html