python 基础

2026/06/251 分钟阅读278

概述

Python 是一种高级的、解释型的编程语言,它支持多种编程范式,包括面向对象、命令式、函数式和过程式编程。Python 的设计哲学强调代码的可读性和简洁性,尤其是通过使用缩进来表示代码块。

Python 的主要特点包括:

  1. 易于学习和使用
  2. 高级数据类型(如列表、字典和集合)
  3. 动态类型系统
  4. 支持面向对象编程
  5. 大量的第三方库和框架
  6. 跨平台支持

目标

基础

  1. Python 环境搭建
  2. 数据类型
  3. 条件控制
  4. 循环语句
  5. 列表推导式
  6. 函数
  7. 装饰器
  8. 面向对象

第三方库

  1. requests
  2. pandas
  3. jsonpath
  4. pymysql
  5. locust
  6. pytest
  7. Path
  8. playwright
  9. SQLAlchemy
  10. jinja2

里程碑

Python 环境管理

  • Pyenv:占用较小,适合纯 Python 应用;
  • Anaconda:占用比较大,内置了很多数据科学用的库;

UI 自动化

利用 playwright 框架

接口自动化

Pytest + Requests + Allure + Jenkins

conftest.py 文件钩子配置

def pytest_assertrepr_compare(op, left, right):
    if op == "==":
        if not isinstance(right, type(left)):
            return [
                f"断言错误,实际值与期望值的数据类型不一致,实际值数据类型为:{type(left)},期望值为:{type(right)}",
                f"实际值为:{left},期望值为:{right}",
            ]
        else:
            return [
                f"断言错误,实际值与期望值不一致,实际值为:{left},期望值为:{right}",
            ]

    if op == "in":
        if isinstance(left, str) and isinstance(right, str):
            return [
                f"期望{left} 是{right} 的子串,实际{left} 不是{right} 的子串,"
            ]
        elif isinstance(right, list) or isinstance(right, set) or isinstance(right, tuple):
            return [
                f"期望{left} 是集合{right} 中的一个元素,实际集合{right} 中没有{left} 元素"
            ]
        elif isinstance(right, dict):
            return [
                f"期望{left} 是字典{right} 中的一个key,实际字典{right} 中没有值为{left} 的key"
            ]
        else:
            return [
                f"期望{left} 是{right} 中的一部分,实际上{left} 并不是{right} 的一部分"
            ]

    if op == "not in":
        if isinstance(left, str) and isinstance(right, str):
            return [
                f"期望{left} 不是{right} 的子串,实际{left} 是{right} 的子串,"
            ]
        elif isinstance(right, list) or isinstance(right, set) or isinstance(right, tuple):
            return [
                f"期望{left} 不是集合{right} 中的一个元素,实际集合{right} 中有{left} 元素"
            ]
        elif isinstance(right, dict):
            return [
                f"期望{left} 不是字典{right} 中的一个key,实际字典{right}中有值为{left} 的key"
            ]
        else:
            return [
                f"期望{left} 不是{right} 中的一部分,实际上{left} 是{right} 的一部分"
            ]


def pytest_collection_modifyitems(items):
    """
    测试用例收集完成时,将收集到的item的name和nodeid进行中文显示
    :param items:
    :return:
    """
    for item in items:
        item.name = item.name.encode('utf-8').decode('unicode_escape')
        item._nodeid = item._nodeid.encode('utf-8').decode('unicode_escape')

Python 后端服务

FastAPI

  1. FastAPI 中Body、Cookie、Header、Query和 Path的区别

Django

经验

动态导包

import os
import importlib

def import_all_modules_from_package(package_name):
    # 获取当前文件的目录
    package_dir = os.path.dirname(__file__)
    # 遍历目录及其子目录中的所有文件
    for root, _, files in os.walk(package_dir):
        for file in files:
            # 只处理以 .py 结尾且不是 __init__.py 的文件
            if file.endswith(".py") and file != "__init__.py":
                # 获取模块的相对路径
                module_path = os.path.relpath(os.path.join(root, file), package_dir)
                # 构建模块的名称
                module_name = f"{package_name}." + module_path.replace(os.sep, ".")[:-3]
                # 导入模块
                importlib.import_module(module_name)

# 导入当前包中的所有模块
import_all_modules_from_package(__name__)

协程/异步编程

有点儿类似于 JS 的 Promise.all

# -*- coding: utf-8 -*-
import asyncio

async def good():
    print('good')
    return 'good'

async def main():
    # result = asyncio.gather(*[good() for i in range(10)])
    result = await asyncio.gather(*[good() for i in range(10)])
    for i in result:
        print('nnn ' + i)

asyncio.run(main())

集合

list1 = [1, 2, 3, 4]
list2 = [2, 4, 5]

# 将列表转换为 set
set1 = set(list1)
set2 = set(list2)

union_set1 = set1 | set2
union_set2 = set1 & set2
union_set3 = set1 - set2
union_set4 = set1 ^ set2

# 将并集转换回列表
union_list1 = list(union_set1)
union_list2 = list(union_set2)
union_list3 = list(union_set3)
union_list4 = list(union_set4)

print(f'并集 | :{union_list1}')
print(f'交集 & :{union_list2}')
print(f'差集 - :{union_list3}')
print(f'对称差集 ^ :{union_list4}')