python高级用法总结
·
目录
一、前言
本文用来记录并分享下python中的一些高级用法,都是日常在工作中遇到,且很优雅、很pythonic的语法。仅用来学习回顾。
后面若遇到其他的新知识,会同步更新此文。
二、python高级写法
2.1 、装饰器
装饰器说白了就是函数套函数,通常可以用来做日志记录、参数注入。使用方式@装饰器函数,被装饰器装饰的函数调用时,会先进入装饰器函数中,由装饰器函数执行被装饰函数。下面是一个记录操作日志的装饰器写法。
def track_record(func):
"""操作日志记录"""
@wraps(func)
def wrapper(*args, **kwargs):
# 日志信息数据
user_id, user_name, menu_id, operation_msg = get_router_mapping()
log_data = {
'user_id': user_id,
'user_name': user_name,
'operation_time': datetime.datetime.now(),
'operation_msg': operation_msg,
'menu_id': menu_id,
}
# 调用原函数
try:
result = func(*args, **kwargs)
except:
log_data['status'] = 0
raise
else:
log_data['status'] = 1
finally:
insert_Tract_record(log_data)
return result
return wrapper
# 使用
@track_record
def delete_tpicz():
xxx
2.2、生成器(yeild)
使用yeild的函数不会返回所有数据,而是会返回一个生成器对象,通过next或for去消费。yeild的地方相当于一个暂停命令,下次运行会在暂停的位置继续往下执行。
# 斐波那契数列
def fib(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
fibObj = fib(100)
for x in fibObj:
print(x, end=' ')
2.3、上下文管理器(@contextmanager)
from contextlib import contextmanager
# 可以用with的session上下文管理器
@contextmanager
def session_scope() -> Iterator:
SessionLocal = get_session_factory()
session = SessionLocal()
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()
# 使用(会自动关闭)
with session_scope() as session:
session.query(xxx).filter().all()
# 底层实现的with上下文管理器(有__enter__和__exit__)
class contextDemo(object):
def __init__(self, filename):
self.filename = filename
# with进去时调用
def __enter__(self):
self.f = open(self.filename, 'a+')
return self.f
# with结束时调用
def __exit__(self, exc_type, exc_val, exc_tb):
"""
:param exc_type: 异常类型
:param exc_val: 异常值
:param exc_tb: 堆栈
"""
self.f.close()
2.4、类型注解(@dataclass)
类似于Pydantic的静态类型,不同的是只有提示没有类型验证、转换功能。
from dataclasses import dataclass
@dataclass
class apiConfig():
user_id: str
args: str
# 会自动做静态参数校验
def run(conf: apiConfig):
pass
2.5、值缓存(@lru_cache)
from functools import lru_cache
@lru_cache(maxsize=1)
def getConfig():
# 获取配置xxx
conf = {}
return conf
更多推荐



所有评论(0)