文章目录
python __xxx__系统内部规定
def __new__(cls):
# 声明一个类 优于__init__() 同类中 不会执行__init__ 除非函数内声明
return super().__new__(cls) # 建议使用 __init__ 会执行
def __init__(self):
# 初始化类 以及 初始时需要做的事以及声明的参数
def __call__(self):
# 实例能够像函数一样被调用 与__init__ 同级
def __str__(self):
# 初始化类 打印内容 与__init__ 同级
def __del__(self):
# 程序运行完 销毁对象
__name__ # 类名
__file__ # 文件的路径
pip 安装 GitHub 库
pip install git+https://github.com/[repo所有者]/[repo] @[分支名称]
特殊符号@和不定参数的使用
@ # 现有函数增加额外的功能,常用于插入日志、性能测试、事务处理等等
*arg # 不定个数的参数元组
**kwargs # 把多余的参数以字典的形式收集起来
# Exception 是异常的类型
# args 是自已提供的异常参数
# 一个异常可以是一个字符串,类或对象
raise [Exception (args, tracebac)]
:param 参数名: 参数描述信息
timeit测量小代码片段的执行时间
# 可以在内部测试代码
if __name__ == '__main__':
pass
# 测试小代码块时间
import timeit
timeit.timeit(stmt="[i for i in range(1000)]", number=100000)
timeit.repeat(stmt="[i for i in range(1000)]", repeat=2, number=100000)
# stmt: 这个参数就是statement,可以把要进行计算时间的代码放在里面。
# 他可以直接接受字符串的表达式,也可以接受单个变量,也可以接受函数
# number: 执行次数
# repeat: 重复次数, 因此repeat适合求出一个代码的稳定时间
正则r的用法
# 在 Windows 下,文件路径前需要加 r 取消 \ 转义或者将 \ 用 \\ 转义,否则会转码错误。
# rt 模式下,python 在读取文本时会自动把 \r\n 转换成 \n
# wt 模式下,Python 写文件时会用 \r\n 来表示换行。
with open(r'C:\Users\Administrator\Desktop\s.txt','wt') as fileout:
fileout.write("写一行中文试试\n")
with open(r'C:\Users\Administrator\Desktop\s.txt','rt') as filein:
print(filein.readline())
字符判断
str.isalnum() # 判断所有字符都是数字或者字母
str.isalpha() # 判断所有字符都是字母
str.isdigit() # 判断所有字符都是数字
str.islower() # 判断所有字符都是小写
str.isupper() # 判断所有字符都是大写
str.istitle() # 判断所有单词都是首字母大写,像标题
str.isspace() # 判断所有字符都是空白字符、\t、\n、\r
str.upper() # 把所有字符中的小写字母转换成大写字母
str.lower() # 把所有字符中的大写字母转换成小写字母
str.capitalize() # 把第一个字母转化为大写字母,其余小写
str.title() # 把每个单词的第一个字母转化为大写,其余小写
# str:变量名
万能的小工具functools
from functools import *
reduce() # 会对参数序列中元素进行累积
逆序排序方法
# 方法一
list[::-1]
# 方法二
# 会直接修改了原来的数据
list.reverse()
# 方法三
# 返回的是一个把序列值经过反转之后的迭代器
# 使用next(),list()或者使用遍历的方法
reversed(list)
isinstance(object,classinfo)与type()区别
# 返回类型不同
isinstance包含type,它是判断类型的一个函数,返回类型为布尔值
type是返回var的数据属性
if isinstance(tr, bs4.element.Tag):
return True
type(tr)
map :change element type in list
map(function, iterable, ...)
# each element squared
map(square, [1,2,3,4,5])
# change str to int
list_str = '88 89 90 100 100 1200'
a = list(map(int,list_str.split()))
yield关键字
"""
yield是关键字
一次返回一次结果,在每个结果之间挂起当前状态,下次调用直接继续当前的状态.
next()函数
next(iterator[, default])
send()函数
将string中的数据发送到连接的套接字 它前面为什么需要next()
"""
# 生成器: 一次一个结果 生成列表[0, 1, 2, 3, 4]
L = [x for x in range(5)]
# next() and yield
def test():
di = ['第一次', '第二次', '第三次']
for i in di:
# te没有类型
te = yield i
print("{}te是:{}".format(i, te))
print("te:'我怎么没有值'")
t = test()
print(next(t))
print(next(t))
# send() and yield
def test():
di = ['第一次', '第二次', '第三次']
for i in di:
te = yield i
print("{}te是:{}".format(i, te))
print("te:'我怎么是{}'".format(te))
t = test()
print(next(t))
# if it is None in send(), like next()
print(t.send(2))
自定义异常处理模块
traceback
介绍:存储在
sys.last_traceback
中的对象类型变量,并作为sys.exc_info()
的第三项被返回。文档:打印或检索堆栈回溯
#!/usr/bin/env python3
import traceback
import sys
def func():
raise Exception("-- func exception --")
def main():
try:
func()
except Exception as e:
# exc_obj <Object traceback>
exc_type, exc_value, exc_obj = sys.exc_info()
# sys.exc_info()[2].tb_frame.f_back
# sys._getframe().f_code.co_name
# to print exception info
traceback.print_tb(exc_obj)
if __name__ == "__main__":
main()
内存处理适用于Linux系统
获取soft
上限和hard
上限
import resource
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
# 8G = 8 * 1024^6
设置程序最大内存
resource.setrlimit(resource.RLIMIT_AS, (0.05*1024^6, hard))
# MemoryError
下划线
_xxx # 仅供内部使用
xxx_ # 解决关键字命名冲突
__xxx # 触发名称修饰 防止变量在子类被重写
__xxx__ # python 特殊方法
_ # 临时值
数据结构
枚举
枚举类不能用来实例化对象,但不妨碍访问枚举类中的成员。
from enum import Enum
class RGB(Enum):
RED = 1
GREEN = 1
BLUE = 1
通过value
获取枚举类中变量值,name
获取枚举类中变量名。
RGB.RED # <enum 'RGB'> <RGB.RED: 1>
RGB.RED.value # <class 'int'> 1
REG.RED.name # <class 'str'> 'RED'
可以通过__members__
属性访问枚举类中的各个成员。
RGB.__members__ # <class 'mappingproxy'>
RGB.__members__.item() # <class 'odict_items'>
for name, member in RGB.__members__.items():
name # <class 'str'> 'RED'
member # <enum 'RGB'> <RGB.RED: 1>
可以借助@unique
装饰器,避免枚举类中出现相同值的成员。
from enum import Enum, unique
@unique
class RGB(Enum):
RED = 1
GREEN = 1
BLUE = 1
# ValueError: duplicate values found in <enum 'RGB'>: GREEN -> RED, BLUE -> RED
原型继承
object与type的区别
class Type(type):
pass
class Object(object):
pass
如上所述如果两个类都没有写__init__
与__new__
,那么当我们调用这两个类时,可以看出明显的区别。
Type()
会默认去执行__new__
函数,Object()
会默认去执行__init__
函数。
这个时候有个疑问就是为什么有个默认初始化