我的 Python 笔记

本文最后更新于:2022年3月23日 晚上

一些实际开发中总结的 Python 经验~

获取字典的值

d = {'a': 1, 'b': 2}

一般我们会直接用 d['a'] 获取字典的值,但是如果不小心写了 d['c'] ,字典中并没有 'c' 的键,就会报错。

更好的方法是使用 get() 方法~

a = d.get('a')  # a = 1
c = d.get('c')  # 不存在键'c', c = None
d = d.get('d', 0)  # 不存在键'd', d = 0, 第二个参数为当键不存在的时候的默认返回值

读、写或删除文件、文件夹

读、写或删除文件、文件夹前先判断其是否存在!

import os

p = 'test.txt'
if os.path.exist(p):
	os.remove(p)  # 删除该文件

os.path 官方文档:https://docs.python.org/zh-cn/3.8/library/os.path.html

几个常用的接口:

# os库
os.path.exist(p)  # 判断文件或文件夹p是否存在
os.path.isfile(p)  # p是文件?
os.path.isdir(p)  # p是文件夹?
os.path.abspath(p)  # 将相对路径p转为绝对路径

os.remove(p)  # 删除文件p, 不能用于删除文件夹
os.rmdir(p)  # 删除文件夹p, 文件夹必须为空

# shutil库
shutil.rmtree(p)  # p为文件夹,递归地删除p及其内部所有文件

尽量处理可能发生的异常

处理异常当然是应该的,否则一旦程序运行中出现异常就会导致程序无法继续运行~

几点经验:

  • 尽量用 if 判断替代异常处理。尽可能避免异常的出现;
  • 尽可能小范围的捕获异常。尽量避免使用 BaseException
  • 如果捕获了异常,建议将错误信息打印出来方便调试。

重试机制

times = 3
while times > 0:
    # do something
    times -= 1

超时机制

超时处理应该是比较常用的一种逻辑,比如重试机制。

t = time.time()
while True:
    # do something
    if time.time() - t > 3:
        break  # 超时3s则跳出循环

单例模式

class MyClass:
    _instance = None  # 唯一实例

    def __new__(cls, *args, **kw):
        if cls._instance is None:
            cls._instance = object.__new__(cls)
        return cls._instance

多线程

Python 中多线程一般使用 threading 库,官方文档:https://docs.python.org/zh-cn/3/library/threading.html。

具体使用方法就不细说了,这里主要说一下用装饰器来封装一个多线程方法,如下,然后后续任何需要多线程执行的方法都只需要在定义前加上 @thread_runner 即可,非常方便~

def thread_runner(func):
    def wrapper(*args, **kw):
        threading.Thread(target=func, args=args, kwargs=kw).start()
    return wrapper

使用:

@thread_runner
def new_thread():
    while True:
        # do something

线程之间的通信

在 Python 中多线程之间的通信我了解并使用了两种~

  • 使用线程安全的队列类 queue

    以较常用的先进先出队列类 queue.Queue 为例,只要在作用于范围内,不同线程之间都可以正常的入队和出队。

    import queue
    pipe = queue.Queue()  # 先进先出的队列
    pipe.push(obj)  # 将obj存到队列尾
    pipe.get()  # 获取队列首部的对象
  • 在类的某个线程方法中使用类的属性

    我常使用此方法来终止线程~

    class MyThread:
        def __init__():
            self.run = False
        
        @thread_runner
        def run_thread(self):
            self.run = True
            while self.run:
                # do something
        
        def stop(self):
            self.run = False
    
    
    if __name__ == '__main__':
        thread = MyThread()
        thread.run_thread()  # 启动线程
        # do something
        thread.stop()  # 停止线程

字符串格式化

字符串拼接的方法很多,比如说使用 + 运算符,或者使用 format(value[, format_spec]) 函数,但我个人认为最方便好用的是 f-string ,只需要在普通字符串前加一个 f ,在需要插入变量值的地方用大括号 {} 包裹变量即可,甚至都不需要使用 str() 将变量转为字符串。示例:

d = 3.14
string = f'PI is approximately equal to {d}.'

我的 Python 笔记
https://mxy493.xyz/2020111660580/
作者
mxy
发布于
2020年11月16日
许可协议