1. Python视频
1) 多层装饰器
USER_INFO = {} def check_login(func): def inner(*args, **kwargs): if USER_INFO.get('is_login', None): ret = func(*args, **kwargs) return ret else: print('please login') return inner def check_admin(func): def inner(*args, **kwargs): if USER_INFO.get('type', None) == 2: ret = func(*args, **kwargs) return ret else: print('no permission') return inner @check_login @check_admin def index(): # manager print('Index') def home(): # user print('home') def login(): user = input('input username >>>') pwd = input('input password >>>') if user == 'admin' and pwd == 'admin': USER_INFO['is_login'] = True USER_INFO['type'] = 2 else: if user == 'wayne' and pwd == 'phuck': USER_INFO['is_login'] = True USER_INFO['type'] = 1 def main(): while True: inp = input('1.login 2.information 3.management >>>') if inp == '1': login() elif inp == '2': home() elif inp == '3': index() main()
2) 字符串格式化
- 百分号方式
%[(name)][flags][width].[precision]typecode
1.顺序传入参数
2.指定名称传入参数
3.保留小数点后几位
4.如果出现占位符,只写%%,打印时%
- Format方式
[[fill]align][sign][#][0][width][,][.precision][type]
# s1 = 'i am %s' %'alex' # s1 = 'i am %s age %d' %('alex',18) # s1 = 'i am %(name)s age %(age)d' %{'name':'alex','age':18} # s1 = 'percent %.2f' %99.97623 # s1 = 'i am %(pp).2f' %{'pp':123.425556} # s1 = 'i am %.2f %%' %123.43556 # print(s1) s1 = 'i am {}, age {}, {}'.format('seven',18,'alex') s1 = 'i am {}, age {}, {}'.format(*['seven',18,'alex']) s1 = 'i am {0}, age {1}, really {0}'.format('seven',19) s1 = 'i am {0}, age {1}, really {0}'.format(*['seven',19]) s1 = 'i am {name}, age {age}, really {name}'.format(name='seven',age=20) s1 = 'i am {name}, age {age}, really {name}'.format(**{'name':'seven','age':20}) s1 = 'i am {0[0]}, age {1[1]}, really {0[2]}'.format([1,2,3],[11,22,33]) s1 = 'i am {:s}, age {:d}, money {:f}'.format('seven',18,8888.1) s1 = 'i am {:s}, age {:d}'.format(*['seven',18]) s1 = 'i am {name:s}, age {age:d}'.format(name='seven',age=18) s1 = 'i am {name:s}, age {age:d}'.format(**{'name':'seven','age':18}) s1 = 'numbers:{:#b},{:#o},{:#d},{:#x},{:#X},{:%}'.format(15,15,15,15,15,15,87623,2) s1 = 'numbers:{0:b},{0:o},{0:d},{0:x},{0:X},{1:%}'.format(15,16) s1 = 'numbers:{num:b},{num:o},{num:d},{num:x},{num:X},{num:%}'.format(num=15) print(s1)
3) 生成器
- 一个函数调用时返回一个迭代器,那这个函数就叫做生成器(generator);
- 如果函数中包含yield语法,那这个函数就会变成生成器;
>>> def func(): ... yield 1 ... yield 2 ... yield 3 ... yield 4 ... >>> >>> temp = func() >>> temp <generator object func at 0x00000207CC064A40> >>> temp.__next__() 1 >>> temp.__next__() 2 >>> temp.__next__() 3 >>> temp.__next__() 4 >>> temp.__next__() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>
def func(): print(111) yield 1 print(222) yield 2 print(333) yield 3 ret = func() r1 = ret.__next__() # 进入函数找到yield,获取yield后面的数据 print(r1) r2 = ret.__next__() print(r2) r3 = ret.__next__() print(r3) # r4 = ret.__next__() # print(r4)
def myrange(arg): start = 0 while True: if start > arg: return yield start start += 1 ret = myrange(3) r = ret.__next__() print(r) r = ret.__next__() print(r) r = ret.__next__() print(r) r = ret.__next__() print(r)
4) 迭代器
- 迭代器是访问集合元素的一种方式。
- 迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。
- 迭代器只能往前不会后退,不过这也没什么,因为人们很少在迭代途中往后退。
- 迭代器的一大优点是不要求事先准备好整个迭代过程中所有的元素。
迭代器仅仅在迭代到某个元素时才计算该元素,而在这之前或之后,元素可以不存在或者被销毁。
这个特点使得它特别适合用于遍历一些巨大的或是无限的集合,比如几个G的文件
- 特点:
访问者不需要关心迭代器内部的结构,仅需通过next()方法不断去取下一个内容
不能随机访问集合中的某个值 ,只能从头到尾依次访问
访问到一半时不能往回退
便于循环比较大的数据集合,节省内存
>>> a = iter([1,2,3,4,5]) >>> a <list_iterator object at 0x00000207CC08FFD0> >>> a.__next__() 1 >>> a.__next__() 2 >>> a.__next__() 3 >>> a.__next__() 4 >>> a.__next__() 5 >>> a.__next__() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
5) 递归
def mul(n): if n>1: res = n * mul(n-1) return res else: res = 1 return res r = mul(8) print(r)
6) 模块
- py:模块 (先导入,后使用)
- 内置模块
- 自定义模块
- 第三方模块
- 其他:类库
- 为什么要有模块:将代码归类。
- 导入模块的依据:
import sys for item in sys.path: print(item) sys.path.append('E:\')
- 模块名称的重要性 (不要与内置模块重名)
- 导入模块:
单模块:import
嵌套在文件夹下:from xxx import xxx
from xxx import xxx as ooo
- 第三方模块安装:
- 通过pip3安装: pip3 install requests
- 通过源码: $ python setup.py install
7) 模块 - 序列化
- json 用于[字符串]和[python基本数据类型]间进行转换
- json模块提供了四个功能: dumps, dump, loads, load
# import json # dic = {'k1': 'v1'} # print(dic, type(dic)) # # res = json.dumps(dic) # 将python的基本数据类型转化成字符串类型 # print(res,type(res)) # # # s1 = '{"abc": 123}' # 外面单引号,里面双引号 # dic2 = json.loads(s1) # 将python的字符串类型转化成基本数据类型 # print(dic2, type(dic2)) import json li = [11,22,33] json.dump(li, open('db', 'w')) # dump:列表转化为字符串,再写入文件 li = json.load(open('db','r')) # load:读取文件,并将字符串转化为列表 print(type(li),li)
- 基于天气API获取天气相关JSON数据
import requests import json_test1 response = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=北京') response.encoding = 'utf-8' print(type(response.text)) dic = json_test1.loads(response.text) print(type(dic))
- pickle