-
Python进阶-异步编程进阶
异步上下文管理器 class AsyncDatabase: async def __aenter__(self): await self.connect() return self async def __aexit__(self, exc_type, exc_val, exc_tb): await self.close() 任务管理 async def main(): tasks = [asyncio.create_task(f...…
-
Python进阶-生成器进阶
yield from 语法 def flatten(nested): for sublist in nested: yield from sublistnested = [[1, 2], [3, 4]]print(list(flatten(nested))) # [1, 2, 3, 4] 协程通信 def coroutine(): while True: value = yield print(f"收到: {value}")coro = ...…
-
Python进阶-上下文管理器
自定义上下文管理器 class DatabaseConnection: def __enter__(self): print("连接数据库") return self def __exit__(self, exc_type, exc_val, exc_tb): print("关闭数据库连接") if exc_type: print(f"发生异常: {exc_val}") return False...…
-
Python进阶-元类编程
元类基础 class SingletonMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls]class Singleton(metac...…
-
Python进阶-描述符协议
描述符基础 class Descriptor: def __get__(self, instance, owner): return instance._value def __set__(self, instance, value): if value < 0: raise ValueError("值不能为负") instance._value = valueclass MyClass: attr = De...…
-
Python学习总结-2018年度回顾
学习成果总结2018年我们系统学习了Python的基础知识和实用技巧: 基础语法:变量、数据类型、控制流、函数 面向对象:类、继承、多态 标准库:文件操作、网络请求、数据库 第三方库:pandas、matplotlib、requests 开发工具:虚拟环境、测试、打包核心技能掌握 能够独立开发小型Python项目 掌握常用第三方库的使用 了解Web开发和数据分析基础 具备良好的代码组织和测试习惯下一年规划2019年将继续深入学习: 高级Python特性 框架应用(Dj...…
-
Python实用技巧-缓存策略
函数缓存 from functools import lru_cache@lru_cache(maxsize=128)def expensive_function(n): # 复杂计算 return n * n Redis 缓存 import redisr = redis.Redis(host='localhost', port=6379, db=0)r.set('key', 'value')value = r.get('key') 转载请注明:周志洋的博客 » Pytho...…
-
Python_tips_orm_sqlalchemy
layout: post+title: “Python实用技巧-ORM 与 SQLAlchemy”+date: 2018-12-23 +description: “SQLAlchemy 基础、模型定义、查询操作”+tag: Python ++—++### 模型定义++>python+>from sqlalchemy import Column, Integer, String, create_engine+>from sqlalchemy.ext.declarative ...…
-
Python实用技巧-Web API 开发
基本应用 from flask import Flask, jsonify, requestapp = Flask(__name__)@app.route('/api/users', methods=['GET'])def get_users(): return jsonify({'users': ['Alice', 'Bob']})@app.route('/api/users', methods=['POST'])def create_user(): data = reques...…
-
Python实用技巧-虚拟环境与依赖管理
创建与激活虚拟环境 # Python 3 自带 venv# Windowspython -m venv .venv.venv\\Scripts\\activate# Linux/macOS# python3 -m venv .venv# source .venv/bin/activate pip 常用命令 pip install -U pippip install requests==2.32.0pip freeze > requirements.txtpip install ...…
-
Python实用技巧-机器学习入门
基本分类 from sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifieriris = load_iris()X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target)clf = R...…
-
Python实用技巧-数据可视化
基本绘图 import matplotlib.pyplot as pltx = [1, 2, 3, 4, 5]y = [2, 4, 6, 8, 10]plt.plot(x, y)plt.xlabel('X轴')plt.ylabel('Y轴')plt.title('示例图表')plt.show() 子图 fig, (ax1, ax2) = plt.subplots(1, 2)ax1.plot(x, y)ax2.bar(x, y) 转载请注明:周志洋的博客 » Python实用技巧-数...…
-
Python实用技巧-数据分析入门
数据读取与查看 import pandas as pddf = pd.read_csv('data.csv')print(df.head())print(df.info())print(df.describe()) 数据清洗 df = df.dropna() # 删除空值df = df.drop_duplicates() # 删除重复df['column'] = df['column'].str.strip() # 去除空格 转载请注明:周志洋的博客 » Python实用技巧...…
-
Python实用技巧-网页抓取基础
BeautifulSoup 基础 from bs4 import BeautifulSoupimport requestsresponse = requests.get('https://example.com')soup = BeautifulSoup(response.text, 'html.parser')title = soup.find('title').text 选择器使用 links = soup.find_all('a', href=True)for link in ...…
-
Python实用技巧-并发编程进阶
线程池 from concurrent.futures import ThreadPoolExecutordef worker(x): return x * xwith ThreadPoolExecutor(max_workers=4) as executor: results = list(executor.map(worker, range(10))) 进程池 from concurrent.futures import ProcessPoolExecutorwith P...…
-
Python实用技巧-数据结构进阶
collections 常用类型 from collections import defaultdict, Counter, dequedd = defaultdict(list)counter = Counter("hello")dq = deque([1, 2, 3]) 堆操作 import heapqheap = [3, 1, 4, 1, 5]heapq.heapify(heap)print(heapq.heappop(heap)) # 1 转载请注明:周志洋的博客 » P...…
-
Python基础知识-推导式与生成器表达式
推导式速览 nums = [1, 2, 3, 4]squares = [n*n for n in nums]even_squares = [n*n for n in nums if n % 2 == 0]pairs = {(x, y) for x in range(2) for y in range(2)}index_map = {v: i for i, v in enumerate(nums)} 生成器表达式节省内存 total = sum(n*n for n in range(1...…
-
Python实用技巧-包打包与分发
setup.py 基础 from setuptools import setup, find_packagessetup( name="mypackage", version="0.1.0", packages=find_packages(), install_requires=["requests"],) 构建与安装 python setup.py sdist bdist_wheelpip install dist/mypackage-0.1.0-py3-none-...…
-
Python实用技巧-pytest 测试框架
基本测试 def test_add(): assert add(2, 3) == 5 fixture 使用 import pytest@pytest.fixturedef sample_data(): return [1, 2, 3, 4, 5]def test_sum(sample_data): assert sum(sample_data) == 15 转载请注明:周志洋的博客 » Python实用技巧-pytest 测试框架…
-
Python实用技巧-配置文件处理
configparser 使用 import configparserconfig = configparser.ConfigParser()config.read('config.ini')value = config.get('section', 'key') 环境变量 import osdb_url = os.getenv('DATABASE_URL', 'sqlite:///default.db') 转载请注明:周志洋的博客 » Python实用技巧-配置文件处理…