1. rpartition
作用:从目标字符串的末尾也就是右边开始搜索分割符,将输入的字符分割成3部分
str = "www.baidu.bbbbccom"
output = str.rpartition("b")
print(f"output={output}")
output=('www.baidu.bbb', 'b', 'ccom')
2. contextmanager
定义:实现了上下文协议的对象即为上下文管理器。作用是可以比较精准的分配和释放资源 上下文协议:含有两个函数:
2.1 自定义上下文管理器类
class MyResource:
def __enter__(self):
print('connect to resource!')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('close the resource!')
def query(self):
print('query data')
with MyResource() as r:
r.query()
connect to resource!
query data
close the resource!
2.2 contextmanager修饰符
python 为了更简单的解决上述问题,使用了contextmanager 修饰符进行处理,使得代码更佳简洁
from contextlib import contextmanager
class MyResource:
def query(self):
print("query the data")
@contextmanager
def make_resource():
print("start to the connect")
yield MyResource()
print("end to the connect ")
pass
with make_resource() as r:
r.query()
start to the connect
query the data
end to the connect
3. OrderedDict
4. isinstance
5. hasattr/getattr
|