python基础复习
复习-基础
一、review-base
其他语言吗和python的对比
c vs Python
c语言是python的底层实现,解释器就是由python编写的。
c语言开发的程序执行效率高,开发现率低(内存的管理),python开发效率更高
java vs python
同一个级别,都需要解释器老解释代码。
python简洁方便,java繁琐。
python对于机器学习等强大的类库(模块)。
解释型语言和编译型语言
解释型:边解释边执行(即时翻译)。 代表:python,php,shell 编译型:将所有代码编译成指定文件。如:.dll,然后再去执行.dll文件。 代表:c,c++,Go,c#,java
字节和位的关系
1Byte = 8bit 1Kb = 1024Byte 1Mb = 1024Kb 1Gb = 1024Mb 1Tb = 1024Gb
Python中如何实现 二进制、八进制、十进制、十六进制 之间的转换?
# 其他转十进制 a1 = "010101010101111" int(a1,base=2)# 十进制转二进制
bin(8123)
# 十进制转八进制
oct(87234)
# 十进制转十六进制
hex(3453)
练习:
如 10.3.9.12 转换规则为: 10 00001010 3 00000011 9 00001001 12 00001100 再将以上二进制拼接起来计算十进制结果:00001010 00000011 00001001 00001100 = ?
def ip_func(): ip_num = input("请输入一个ip地址:") s = "" ip_list = ip_num.split(".") for i in ip_list: i = bin(int(i)).lstrip("0b") if len(i) != 8: i = i.zfill(8) s += i return int(s,2) print(ip_func())
字节码和机器码
机器码:是汇编的结果,给操作系统直接读取使用。
字节码:字节码是一种中间状态(中间码)的二进制代码(文件)。需要直译器转译后才能成为机器码。例如:xxx.pyc文件,这个就是python中的中间文件
执行脚本头文件 #!/usr/bin/env python
Linux下运行python文件: 方式一: a.py print(123)python a.py
方式二:
a.py
#!/usr/bin/env python
print(123)赋予可执行权限 .</span>/a.py </pre>
执行脚本头文件 # --coding:utf-8 -*-
py2中:默认编码是asicc(切记!py2一定要用--coding:utf-8 -*-)
py3中:默认编码是utf-8
运算符
v1 = 1 or 2 # 1 v2 = 6 and 1 or 2 and 9 # 1 v3 = 1 or 3 # 1 v4 = 1 and 3 # 3 v5 = 0 and 2 and 1 # 0 v6 = 0 and 2 or 1 # 1 v7 = 0 and 2 or 1 or 4 # 1 v8 = 0 or False and 1 # False
三元表达式/三元运算/三目运算
v1 = 'x1' if 1==1 else 'x2'
常见数据类型
str: split、join、strip、upper
list: append、pop、insert、extend、reverse
tuple:
dict: ....
练习题:
示例1: data = [ {'id': 1, 'name': 'x1'}, {'id': 2, 'name': 'x2'}, {'id': 3, 'name': 'x3'}, {'id': 4, 'name': 'x4'}, ] data_dict = {} for item in data: data_dict[item["id"]] = item print(data_dict) while True: nid = int(input("请输入id")) if nid in data_dict: print("success") else: print("faile")
示例2: data = [ {'id': 1, 'name': 'x1'}, {'id': 2, 'name': 'x2'}, {'id': 3, 'name': 'x3'}, {'id': 4, 'name': 'x4'}, ] data_dict = {} for item in data: data_dict[item["id"]] = item data_dict[2]["name"] = "鹿晗" print(data)
示例3: data = [ {'id': 1, 'name': 'x1','pid':None}, {'id': 2, 'name': 'x2','pid':1}, {'id': 3, 'name': 'x3','pid':2}, {'id': 4, 'name': 'x4','pid':1}, ] data_dict = {} for item in data: item["children"] = [] data_dict[item["id"]] = item # print(data_dict) for item in data: pid = item["pid"] if not pid: continue data_dict[pid]["children"].append(item) print(data_dict)
练习题: v = [11, 232, 122, 13, 122, 31, 123, 111] 获取列表中第二大的数字。 def second(ln): max = 0 s = {} # 查看个数出现的次数然后与赋值给max, for i in range(len(ln)): flag = 0 for j in range(len(ln)): if ln[i] >= ln[j] and i != j: flag = flag + 1 s[i] = flag print(s) if flag > max: max = flag for i in s: if s[i] == max - 1: break print(ln[i]) second([11,232,122,13,122,31,123,111] )
函数的参数
def func(a1, a2=[]): a2.append(a1) return a2v1 = [11, 22, 33]
result1 = func(55)
print(result1) # [55]
result2 = func(44, v1)
print(result2) # [11, 22, 33, 44]
result3 = func(66)
print(result3) # [55, 66]
闭包函数
SQLAlchemy源码 class Query(object):</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> get(self, a1): </span><span style="color: #0000ff;">return</span> 1 <span style="color: #0000ff;">def</span><span style="color: #000000;"> filter(self, a1, a2): </span><span style="color: #0000ff;">return</span> 2 <span style="color: #0000ff;">class</span><span style="color: #000000;"> NewFoo(object): </span><span style="color: #0000ff;">pass</span> <span style="color: #0000ff;">def</span><span style="color: #000000;"> method(name): </span><span style="color: #0000ff;">def</span> inner(*args, **<span style="color: #000000;">kwargs): </span><span style="color: #0000ff;">return</span> getattr(Query, name)(*args, **<span style="color: #000000;">kwargs) </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> inner </span><span style="color: #0000ff;">for</span> name <span style="color: #0000ff;">in</span> [<span style="color: #800000;">'</span><span style="color: #800000;">get</span><span style="color: #800000;">'</span>, <span style="color: #800000;">'</span><span style="color: #800000;">filter</span><span style="color: #800000;">'</span><span style="color: #000000;">]: setattr(NewFoo, name, method(name)) obj </span>=<span style="color: #000000;"> NewFoo() </span><span style="color: #0000ff;">print</span>(obj.get(1111))</pre>
Stark组件 class UserInfoConfig(ModelStark):</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> show_gender(...): </span><span style="color: #0000ff;">if</span><span style="color: #000000;"> is_header: </span><span style="color: #0000ff;">return</span> <span style="color: #800000;">"</span><span style="color: #800000;">性别</span><span style="color: #800000;">"</span> <span style="color: #0000ff;">return</span><span style="color: #000000;"> obj.get_gender_display() </span><span style="color: #0000ff;">def</span><span style="color: #000000;"> show_level(...): </span><span style="color: #0000ff;">if</span><span style="color: #000000;"> is_header: </span><span style="color: #0000ff;">return</span> <span style="color: #800000;">"</span><span style="color: #800000;">级别</span><span style="color: #800000;">"</span> <span style="color: #0000ff;">return</span><span style="color: #000000;"> obj.get_level_display() </span><span style="color: #0000ff;">def</span><span style="color: #000000;"> show_status(...): </span><span style="color: #0000ff;">if</span><span style="color: #000000;"> is_header: </span><span style="color: #0000ff;">return</span> <span style="color: #800000;">"</span><span style="color: #800000;">状态</span><span style="color: #800000;">"</span> <span style="color: #0000ff;">return</span><span style="color: #000000;"> obj.get_status_display() list_display </span>= [<span style="color: #800000;">'</span><span style="color: #800000;">name</span><span style="color: #800000;">'</span>,<span style="color: #800000;">'</span><span style="color: #800000;">email</span><span style="color: #800000;">'</span><span style="color: #000000;">,show_gender,show_level,show_status] </span><span style="color: #0000ff;">def</span><span style="color: #000000;"> get_display(filed_name,title): </span><span style="color: #0000ff;">def</span><span style="color: #000000;"> show(obj,is_header): </span><span style="color: #0000ff;">if</span><span style="color: #000000;"> is_header: </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> title tpl </span>= <span style="color: #800000;">"</span><span style="color: #800000;">get_%s_display</span><span style="color: #800000;">"</span> %<span style="color: #000000;">filed_name </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> getattr(obj,tpl)() </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> show </span><span style="color: #0000ff;">class</span><span style="color: #000000;"> UserInfoConfig(ModelStark): list_display </span>= [<span style="color: #800000;">'</span><span style="color: #800000;">name</span><span style="color: #800000;">'</span>,<span style="color: #800000;">'</span><span style="color: #800000;">email</span><span style="color: #800000;">'</span>,get_display(<span style="color: #800000;">'</span><span style="color: #800000;">gender</span><span style="color: #800000;">'</span>,<span style="color: #800000;">'</span><span style="color: #800000;">性别</span><span style="color: #800000;">'</span>),get_display(<span style="color: #800000;">'</span><span style="color: #800000;">level</span><span style="color: #800000;">'</span>,<span style="color: #800000;">'</span><span style="color: #800000;">级别</span><span style="color: #800000;">'</span>),get_display(<span style="color: #800000;">'</span><span style="color: #800000;">status</span><span style="color: #800000;">'</span>,<span style="color: #800000;">'</span><span style="color: #800000;">状态</span><span style="color: #800000;">'</span>)]</pre>
装饰器
编写装饰器计算函数执行时间
import time from functools import wrapsdef time_this_function(func):
# 作为装饰器使用,返回函数执行需要花费的时间
@wraps(func)
def wrapper(args, **kwargs):
start = time.time()
result = func(args, **kwargs)
end = time.time()
# 函数的名字
print(func.name, end - start)
return result</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> wrapper
if name == 'main':
@time_this_function
def count_number(n):
while n>0:
time.sleep(0.1)
n+=-1
count_number(10)
#!/usr/bin/env python # -*- coding:utf-8 -*-import time
def deco_limit(s, foo= None):
"""
这是个函数装饰器,可以控制访问频率
:param s: 该参数为访问频率,每多少s一次
:param foo: 可选参数,用户自定制装饰器逻辑(比如cookie或状态验证等,执行返回值为False则不执行函数) #该参数实现了,我又删了,不好用,给你提供思路自己做
:return:
"""
def wrpper(func):
"""
该函数接受被修饰函数作为参数,返回装饰器,变量func_identify为变量标识,
存储被修饰函数的name为key,value为调用成功的时间戳。key-second存储为时间频率
:param func: 参数为被修饰函数
:return:
"""
name = func.name
func_identify ={name: 0,'foo': foo, 'second': s}
def inner(args, **kwargs):
"""
执行函数
:param args: 将接收的参数,打包
:param kwargs:
:return:
"""
useable_time = func_identify[name] + func_identify['second']
time_now = time.time()
remain_time = useable_time-time_now
# print(remain_time)
if time_now > useable_time:
func_identify[name] = time_now #设置调用时间
res = func(args,**kwargs)
else:
print('\033[32;1mFunction \033[31;1m{0} \033[0m'
.format(name)+'\033[32;1mcan be used after {0:.2f} seconds later\033[0m'
.format(remain_time))
res = None
return res</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> inner </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> wrpper
#以下为被装饰函数foo1
@deco_limit(5) #在这儿参数为设置调用间隔时间
def foo1(*args, **kwargs):
""" do something with args and kwargs"""
print('执行foo1--everything is ok')
return 'result'#以下为被修饰函数func1
@deco_limit(3) #间隔时间为3秒
def func1(*args, **kwargs):
""" do something with args and kwargs"""
print('执行func1---呱呱呱')
return 'result'print('测试混合执行:')
foo1(1,2,3)
func1(1,2,3)
foo1(2,3,4)
time.sleep(3)
foo1(5,6,7)
time.sleep(2)
foo1(7,9,0)print('\n测试混合执行--:')
func1(1,2,3)
foo1(2,4,52)
func1(2,3,4)
time.sleep(3.2)
foo1(3,4,5)
func1(5,6,7)#-----以下为运行结果------------
测试混合执行:
执行foo1--everything is ok
执行func1---呱呱呱
Function foo1 can be used after 5.00 seconds later
Function foo1 can be used after 2.00 seconds later
执行foo1--everything is ok测试混合执行--:
执行func1---呱呱呱
Function foo1 can be used after 5.00 seconds later
Function func1 can be used after 3.00 seconds later
Function foo1 can be used after 1.80 seconds later
执行func1---呱呱呱
装饰器实现函数重复执行
def counter(num): def outer(func_name): def inner(*args,**kwargs): for i in range(num): func_name() return inner return outer @counter(5) def func(): print(123) func()
装饰器的应用场景?
- flask路由系统 - django用户登录 auth - django csrf token (from django.views.decorators.csrf import csrf_protect,csrf_exempt)
列表生成式 + lambda 表达式
示例1: for i in range(10): pass print(i) # 9
示例2: def func(a1): return a1 + 100 func_list = [] for i in range(10): func_list.append(func) result = func_list[4](10) print(result) # 110
示例3: def func(): return i+100 func_list = [] for i in range(10): func_list.append(func) result = func_list[2]() print(result) # 109
示例4:
func_list = [] for i in range(10): func_list.append(lambda : i+100) result = func_list[2]() print(result) # 109 lambda 是匿名函数,i+100是函数体。只是for循环并没有调用,等到调用的时候再执行
示例5: func_list = [lambda :i+100 for i in range(10)] result = func_list[7]() print(result) # 109 一样
示例6:
def num(): return [lambda x:i*x for i in range(4)] print([m(2) for m in num()]) # [6,6,6,6]
示例7:
def outer(value): def inner(): print(value)</span><span style="color: #0000ff;">return</span><span style="color: #000000;"> inner
func_list = []
for i in range(10):
func_list.append(outer(i))func_list0
func_list1
func_list2
func_list3
func_list4
# 01
2
3
4
生成器
def func(): yield 1 yield 2 yield 3 yield 4 obj = func()
练习:
通过yield自己实现一个类似于py3 range的功能
def func(): for i in range(10): yield i print([i for i in func()])
补充:
py3中list(range(100))与py2中的range(100)相同,直接输出
py3中的range(100)和py2中xrange(100)相同,是生成器,for循环输出值
常见的内置函数
max、min、len、bin、oct、hex、zip
区别:map、filter、reduce(functools)
filter 过滤出符合条件的元素 res = filter(lambda x:x>2 ,[1,2,3]) for i in res: print (i) # 3 map对指定序列做映射 res = map(lambda x:x**2 ,[1,2,3]) for i in res: print (i) # 1 4 9 reduce 对参数序列中元素进行累积 from functools import reduce def add(x,y): return x + y ret = reduce(add,[1,2,3,4,5]) print(ret) # 1+2+3+4+5=15 # 使用lambda函数 ret = reduce(lambda x,y:x+y,[1,2,3,4,5]) print(ret) # 1+2+3+4+5=15
列举常见的内置模块、第三方模块
内置:os、sys、json、time、random、uuid、logging、hashlib、re ...
第三方模块:pandas、numpy、bs4、xpath、requests、scrapy、pymysql、dbutils、gevent-websocket、redis
re模块
match/search区别?
match与search函数功能一样,match匹配字符串开始的第一个位置,search是在字符串全局匹配第一个符合规则的。
简单来说就是:
re.match与re.search的区别:re.match只匹配字符串的开始,
如果字符串开始不符合正则表达式,则匹配失败,函数返回None;
而re.search匹配整个字符串,直到找到一个匹配。
什么是正则的贪婪匹配?
举例说明: 如:String str="abcaxc"; Patter p="ab.*c"; 贪婪匹配:正则表达式一般趋向于最大长度匹配,也就是所谓的贪婪匹配。如上面使用模式p匹配字符串str,结果就是匹配到:abcaxc(ab.*c)。 非贪婪匹配:就是匹配到结果就好,就少的匹配字符。如上面使用模式p匹配字符串str,结果就是匹配到:abc(ab.*c)。
常见正则:手机、邮箱、IP
手机号:^1(3|4|5|6|7|8)[0-9]\d{8}$ 邮箱:\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+.)+[A-Za-z]{2,14} IP:(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d).(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d).(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d).(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)
面向对象
基础
- 基础:三大特性,封装、继承、多态 - 封装,对象、类。 应用场景:分页组件;stark组件 - 继承,多继承继承顺序mro;经典类和新式类;super; 应用场景:drf视图
- 多态
继承:
class Base1(object): def func(self): print('base1.func') super(Base1, self).func()class Base2(object):
def func(self):
print('base2.func')class Foo(Base1, Base2):
passobj = Foo() # Foo > Base1 > Base2
obj.func()
# base1.funcbase2.func
super是多继承顺序,所以会往base2找
# obj = Base1() # Base1
obj.func()
会报错,因为object是父类,没有这个方法
成员
- 字段
</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> Foo:
COUNTRY </span>= <span style="color: #800000;">"</span><span style="color: #800000;">中国</span><span style="color: #800000;">"</span> <span style="color: #008000;">#</span><span style="color: #008000;"> 类变量;静态字段;静态属性</span>
<span style="color: #0000ff;">def</span> <span style="color: #800080;">__init__</span><span style="color: #000000;">(self,name):
self.name </span>= name <span style="color: #008000;">#</span><span style="color: #008000;"> 实例变量;字段;对象属性</span>
obj = Foo('天珠')
</span>-<span style="color: #000000;"> 方法
</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> Foo:
</span><span style="color: #0000ff;">def</span> f1(self): <span style="color: #008000;">#</span><span style="color: #008000;"> 实例方法 Foo().f1()</span>
<span style="color: #0000ff;">pass</span><span style="color: #000000;">
@classmethod
</span><span style="color: #0000ff;">def</span> f2(cls): <span style="color: #008000;">#</span><span style="color: #008000;"> 类方法 Foo.f2() Foo().f2()</span>
<span style="color: #0000ff;">pass</span><span style="color: #000000;">
@staticmethod </span><span style="color: #008000;">#</span><span style="color: #008000;"> 静态方法 Foo.f2() Foo().f2()</span>
<span style="color: #0000ff;">def</span><span style="color: #000000;"> f3():
</span><span style="color: #0000ff;">pass</span>
-<span style="color: #000000;"> 属性
</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> Foo:
@property
</span><span style="color: #0000ff;">def</span><span style="color: #000000;"> start():
</span><span style="color: #0000ff;">pass</span><span style="color: #000000;">
obj </span>=<span style="color: #000000;"> Foo()
obj.start</span></pre>
特殊成员
__init__ # 初始化方法 __new__ # 构造方法 __call__ # 对象后边加括号,触发执行 __getattr__ # 在使用调用属性(方式,属性)不存在的时候触发 __setattr__ # 添加/修改属性会触发它的执行 __delattr__ # 删除属性的时候会触发 __getitem__ ... __dict__ __add__ __str__ __repr__ __iter__ __doc__ __name__ # 输出函数名 __enter__ # with中用 __exit__ class Foo(object): # 上下文管理 def __enter__(self): print('进入') return '1'<span style="color: #0000ff;">def</span> <span style="color: #800080;">__exit__</span><span style="color: #000000;">(self, exc_type, exc_val, exc_tb): </span><span style="color: #0000ff;">print</span>(<span style="color: #800000;">'</span><span style="color: #800000;">出去</span><span style="color: #800000;">'</span><span style="color: #000000;">) obj </span>=<span style="color: #000000;"> Foo() with obj as num: </span><span style="color: #0000ff;">print</span>(123<span style="color: #000000;">,num) </span><span style="color: #800080;">__add__</span> <span style="color: #0000ff;">class</span><span style="color: #000000;"> Foo(object): </span><span style="color: #0000ff;">def</span> <span style="color: #800080;">__init__</span><span style="color: #000000;">(self,num): self.num </span>=<span style="color: #000000;"> num </span><span style="color: #0000ff;">def</span> <span style="color: #800080;">__add__</span><span style="color: #000000;">(self, other): </span><span style="color: #0000ff;">return</span> self.num +<span style="color: #000000;"> other.num obj1 </span>= Foo(11<span style="color: #000000;">) obj2 </span>= Foo(22<span style="color: #000000;">) result </span>= obj1 +<span style="color: #000000;"> obj2 </span><span style="color: #0000ff;">print</span>(result)</pre>
反射
什么是反射: getattr/delattr..... 应用场景? django CBV, django、flask、scrapy等所有的配置文件: v = "django.contrib.sessions.middleware.SessionMiddleware"<span style="color: #0000ff;">def</span><span style="color: #000000;"> import_string(dotted_path): </span><span style="color: #0000ff;">try</span><span style="color: #000000;">: </span><span style="color: #008000;">#</span><span style="color: #008000;"> 'django.contrib.sessions.middleware. SessionMiddleware'</span> module_path, class_name = dotted_path.rsplit(<span style="color: #800000;">'</span><span style="color: #800000;">.</span><span style="color: #800000;">'</span>, 1<span style="color: #000000;">) </span><span style="color: #0000ff;">except</span><span style="color: #000000;"> ValueError: msg </span>= <span style="color: #800000;">"</span><span style="color: #800000;">%s doesn't look like a module path</span><span style="color: #800000;">"</span> %<span style="color: #000000;"> dotted_path six.reraise(ImportError, ImportError(msg), sys.exc_info()[</span>2<span style="color: #000000;">]) </span><span style="color: #008000;">#</span><span style="color: #008000;"> from django.contrib.sessions import middleware</span> module =<span style="color: #000000;"> import_module(module_path) </span><span style="color: #0000ff;">try</span><span style="color: #000000;">: </span><span style="color: #008000;">#</span><span style="color: #008000;"> middleware.SessionMiddleware</span> <span style="color: #0000ff;">return</span><span style="color: #000000;"> getattr(module, class_name) </span><span style="color: #0000ff;">except</span><span style="color: #000000;"> AttributeError: msg </span>= <span style="color: #800000;">'</span><span style="color: #800000;">Module "%s" does not define a "%s" attribute/class</span><span style="color: #800000;">'</span> %<span style="color: #000000;"> ( module_path, class_name) six.reraise(ImportError, ImportError(msg), sys.exc_info()[</span>2])</pre>
</div>
<div class="postDesc">posted @ <span id="post-date">2018-11-20 15:18</span> <a href="https://www.cnblogs.com/hnlmy/">hnlmy</a> 阅读(<span id="post_view_count">3</span>) 评论(<span id="post_comment_count">0</span>) <a href="https://i.cnblogs.com/EditPosts.aspx?postid=9989128" rel="nofollow">编辑</a> <a href="#" onclick="AddToWz(9989128);return false;">收藏</a></div>
</div>
<script type="text/javascript">var allowComments=true,cb_blogId=419389,cb_entryId=9989128,cb_blogApp=currentBlogApp,cb_blogUserGuid='9dd4be1f-fb20-4ca9-9d43-08d5866282ce',cb_entryCreatedDate='2018/11/20 15:18:00';loadViewCount(cb_entryId);var cb_postType=1;</script>