1. Python基础语法精要
Python作为一门解释型高级编程语言,其语法设计以简洁优雅著称。对于零基础学习者而言,掌握基础语法是构建编程思维的第一步。让我们从最核心的语法元素开始剖析:
1.1 变量与数据类型
Python采用动态类型系统,变量声明时无需指定类型。这种灵活性降低了初学者的认知负担,但也需要特别注意类型转换问题。基础数据类型包括:
- 整型(int):如
age = 25 - 浮点型(float):如
price = 19.99 - 字符串(str):如
name = "Alice" - 布尔型(bool):
is_valid = True
注意:Python变量命名应遵循snake_case规范,且区分大小写。避免使用内置关键字如
list、str作为变量名。
类型转换是常见操作:
python复制num_str = "123"
num_int = int(num_str) # 字符串转整型
float_num = float("3.14") # 字符串转浮点
1.2 运算符详解
Python支持丰富的运算符,理解其优先级至关重要:
- 算术运算符:
+ - * / // % ** - 比较运算符:
== != > < >= <= - 逻辑运算符:
and or not - 赋值运算符:
= += -= *= /=
特殊运算符示例:
python复制# 地板除法
print(7 // 2) # 输出3
# 幂运算
print(2 ** 3) # 输出8
# 海象运算符(Python 3.8+)
if (n := len("hello")) > 3:
print(f"长度{n}大于3")
2. 流程控制结构
2.1 条件语句
if-elif-else结构是程序分支的基础:
python复制score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B' # 本例将执行此分支
else:
grade = 'C'
三元运算符简化写法:
python复制status = "合格" if score >= 60 else "不合格"
2.2 循环结构
while循环适用于不确定次数的迭代:
python复制count = 0
while count < 5:
print(f"计数: {count}")
count += 1
for循环配合range函数:
python复制for i in range(5): # 0到4
print(i**2)
# 遍历列表
fruits = ['apple', 'banana', 'cherry']
for idx, fruit in enumerate(fruits):
print(f"索引{idx}: {fruit}")
循环控制语句:
break:立即退出循环continue:跳过当前迭代else:循环正常结束时执行
3. 函数定义与使用
3.1 函数基础
函数定义使用def关键字:
python复制def greet(name, greeting="Hello"):
"""返回问候语"""
return f"{greeting}, {name}!"
print(greet("Alice")) # 使用默认参数
print(greet("Bob", "Hi")) # 覆盖默认参数
提示:文档字符串(
"""...""")是良好的编程习惯,可通过help(greet)查看。
3.2 参数传递机制
Python参数传递是"对象引用传递",理解这点至关重要:
python复制def modify_list(lst):
lst.append(4) # 修改会影响原始列表
numbers = [1, 2, 3]
modify_list(numbers)
print(numbers) # 输出[1, 2, 3, 4]
参数类型:
- 位置参数
- 关键字参数
- 可变参数:
*args接收元组 - 关键字可变参数:
**kwargs接收字典
4. 数据结构深入
4.1 列表(List)
列表是Python中最灵活的序列类型:
python复制# 列表创建
numbers = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, [4, 5]]
# 切片操作
print(numbers[1:3]) # [2, 3]
print(numbers[::-1]) # 反转列表
# 列表推导式
squares = [x**2 for x in range(10)]
常用列表方法:
append()/extend():添加元素insert():指定位置插入remove()/pop():删除元素sort()/reverse():排序反转
4.2 字典(Dict)
字典存储键值对,查找效率O(1):
python复制# 字典创建
person = {
"name": "Alice",
"age": 25,
"skills": ["Python", "SQL"]
}
# 访问元素
print(person.get("age", 0)) # 安全获取,不存在返回0
# 字典推导式
square_dict = {x: x*x for x in range(5)}
字典常用操作:
keys()/values()/items():获取视图update():合并字典setdefault():安全添加键
5. 文件操作与异常处理
5.1 文件读写
使用with语句自动管理文件资源:
python复制# 写入文件
with open("data.txt", "w", encoding="utf-8") as f:
f.write("Hello\nWorld")
# 读取文件
with open("data.txt", "r") as f:
content = f.readlines() # 返回列表
文件模式:
'r':读取(默认)'w':写入(覆盖)'a':追加'b':二进制模式'+':读写模式
5.2 异常处理
try-except结构处理运行时错误:
python复制try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零")
except Exception as e:
print(f"发生错误: {e}")
else:
print("未发生异常")
finally:
print("始终执行")
常见内置异常:
IndexError:索引越界KeyError:字典键不存在TypeError:类型错误ValueError:值错误FileNotFoundError:文件不存在
6. 面向对象编程
6.1 类与对象
类定义使用class关键字:
python复制class Dog:
"""犬类"""
species = "Canis familiaris" # 类属性
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
def description(self):
return f"{self.name} is {self.age} years old"
# 实例化
my_dog = Dog("Buddy", 5)
print(my_dog.description())
6.2 继承与多态
继承实现代码复用:
python复制class Bulldog(Dog): # 继承Dog类
def run(self, speed="slow"):
return f"{self.name} runs {speed}ly"
# 方法重写
class GoldenRetriever(Dog):
def description(self):
return f"Golden {super().description()}"
特殊方法示例:
python复制class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
7. 模块与包管理
7.1 模块导入
模块是Python代码的组织单元:
python复制# 导入整个模块
import math
print(math.sqrt(16))
# 导入特定函数
from random import randint
print(randint(1, 10))
# 别名导入
import numpy as np
7.2 包结构
包是模块的集合,需包含__init__.py文件:
code复制my_package/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
相对导入示例:
python复制# 在module2.py中
from .module1 import func1
from ..subpackage.module3 import func2
8. 实用标准库模块
8.1 os与sys模块
操作系统交互:
python复制import os
import sys
# 文件操作
print(os.listdir('.')) # 当前目录内容
os.makedirs('temp', exist_ok=True)
# 系统参数
print(sys.argv) # 命令行参数
print(sys.path) # Python路径
8.2 datetime与json
日期与JSON处理:
python复制from datetime import datetime, timedelta
import json
# 日期计算
now = datetime.now()
tomorrow = now + timedelta(days=1)
# JSON转换
data = {'name': 'Alice', 'age': 25}
json_str = json.dumps(data) # 字典转JSON字符串
loaded = json.loads(json_str) # JSON字符串转字典
9. 虚拟环境管理
9.1 venv创建
隔离项目依赖:
bash复制# 命令行创建
python -m venv myenv
# 激活环境
# Windows: myenv\Scripts\activate
# Unix/macOS: source myenv/bin/activate
9.2 依赖管理
使用requirements.txt:
bash复制# 生成依赖文件
pip freeze > requirements.txt
# 安装依赖
pip install -r requirements.txt
10. 项目实战:数据分析
10.1 Pandas基础
数据框操作:
python复制import pandas as pd
# 创建DataFrame
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
# 数据操作
print(df.describe()) # 统计摘要
filtered = df[df['Age'] > 25] # 过滤
10.2 Matplotlib可视化
绘制简单图表:
python复制import matplotlib.pyplot as plt
# 折线图
x = [1, 2, 3]
y = [2, 5, 3]
plt.plot(x, y)
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('简单图表')
plt.show()
11. 调试与性能优化
11.1 pdb调试
使用内置调试器:
python复制import pdb
def buggy_func(x):
pdb.set_trace() # 设置断点
return x * 2 + 1
调试命令:
n:执行下一行c:继续执行p:打印变量q:退出调试
11.2 性能分析
使用timeit模块:
python复制from timeit import timeit
code = '"-".join(str(n) for n in range(100))'
time = timeit(code, number=10000)
print(f"执行时间: {time:.3f}秒")
12. 进阶特性
12.1 生成器与迭代器
内存高效处理:
python复制def fibonacci(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
for num in fibonacci(100):
print(num)
12.2 装饰器
函数增强工具:
python复制def log_time(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__}耗时: {time.time()-start:.3f}s")
return result
return wrapper
@log_time
def heavy_computation():
time.sleep(1)
13. 项目结构规范
13.1 典型布局
标准项目结构:
code复制project/
│── README.md
│── setup.py
│── requirements.txt
│── mypackage/
│ │── __init__.py
│ │── module1.py
│ └── tests/
│ └── test_module1.py
└── docs/
└── conf.py
13.2 打包发布
使用setuptools:
python复制# setup.py示例
from setuptools import setup, find_packages
setup(
name="mypackage",
version="0.1",
packages=find_packages(),
install_requires=['numpy>=1.0'],
)
14. 测试驱动开发
14.1 unittest框架
编写测试用例:
python复制import unittest
def add(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertNotEqual(add(0, 0), 1)
if __name__ == '__main__':
unittest.main()
14.2 pytest进阶
更简洁的测试:
python复制# test_sample.py
def test_add():
assert add(2, 3) == 5
def test_add_negative():
assert add(-1, -1) == -2
运行测试:
bash复制pytest test_sample.py -v
15. Web开发入门
15.1 Flask基础
最小Web应用:
python复制from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)
15.2 路由与模板
动态路由示例:
python复制from flask import render_template
@app.route('/user/<username>')
def show_user(username):
return render_template('profile.html', name=username)
模板文件templates/profile.html:
html复制<h1>Hello {{ name }}!</h1>
16. 并发编程
16.1 多线程
threading模块基础:
python复制import threading
import time
def worker(num):
print(f"Worker {num}开始")
time.sleep(1)
print(f"Worker {num}结束")
threads = []
for i in range(3):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
for t in threads:
t.join()
16.2 异步IO
asyncio示例:
python复制import asyncio
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(say_after(1, 'hello'))
task2 = asyncio.create_task(say_after(2, 'world'))
await task1
await task2
asyncio.run(main())
17. 数据库交互
17.1 SQLite操作
内置数据库使用:
python复制import sqlite3
# 连接数据库
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS stocks
(date text, trans text, symbol text, qty real, price real)''')
# 插入数据
cursor.execute("INSERT INTO stocks VALUES ('2023-01-01','BUY','AAPL',100,145.67)")
# 提交并关闭
conn.commit()
conn.close()
17.2 SQLAlchemy ORM
对象关系映射:
python复制from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
# 创建引擎和表
engine = create_engine('sqlite:///users.db')
Base.metadata.create_all(engine)
18. 网络编程
18.1 请求处理
requests库使用:
python复制import requests
response = requests.get('https://api.github.com')
print(response.status_code)
print(response.json())
带参数请求:
python复制params = {'q': 'python', 'page': 1}
r = requests.get('https://api.github.com/search/repositories', params=params)
print(r.url) # 查看最终请求URL
18.2 简单服务器
socket编程基础:
python复制import socket
HOST = '127.0.0.1'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
19. 代码质量保障
19.1 代码规范
PEP 8检查:
bash复制# 安装检查工具
pip install pycodestyle
# 检查文件
pycodestyle your_script.py
自动格式化:
bash复制pip install black
black your_script.py
19.2 类型提示
静态类型检查:
python复制from typing import List, Dict
def greet_all(names: List[str]) -> Dict[str, int]:
return {name: len(name) for name in names}
mypy检查:
bash复制pip install mypy
mypy your_script.py
20. 项目部署
20.1 WSGI部署
使用Gunicorn:
bash复制pip install gunicorn
gunicorn -w 4 -b 127.0.0.1:8000 your_app:app
20.2 Docker打包
Dockerfile示例:
dockerfile复制FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "-b", "0.0.0.0:8000", "your_app:app"]
构建与运行:
bash复制docker build -t your-app .
docker run -d -p 8000:8000 your-app
21. 性能优化技巧
21.1 数据结构选择
不同操作的时间复杂度:
- 列表:
O(1)访问,O(n)插入/删除 - 集合:
O(1)成员检测 - 字典:
O(1)查找/插入
集合去重示例:
python复制# 比列表遍历更高效
duplicates = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(duplicates))
21.2 内存管理
生成器节省内存:
python复制# 避免一次性加载大文件
def read_large_file(file_path):
with open(file_path) as f:
for line in f:
yield line.strip()
for line in read_large_file('huge.log'):
process(line)
22. 设计模式实践
22.1 单例模式
实现方式:
python复制class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
a = Singleton()
b = Singleton()
print(a is b) # True
22.2 工厂模式
简单工厂示例:
python复制class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
def get_pet(pet="dog"):
pets = {"dog": Dog(), "cat": Cat()}
return pets[pet]
23. 安全编程实践
23.1 输入验证
防止注入攻击:
python复制import re
def validate_username(username):
if not re.match(r'^[a-zA-Z0-9_]{3,20}$', username):
raise ValueError("无效用户名")
return True
23.2 密码安全
使用hashlib:
python复制import hashlib
import os
def hash_password(password):
salt = os.urandom(32)
key = hashlib.pbkdf2_hmac(
'sha256',
password.encode('utf-8'),
salt,
100000
)
return salt + key
24. 跨平台开发
24.1 路径处理
使用pathlib:
python复制from pathlib import Path
# 跨平台路径操作
config_path = Path.home() / 'config' / 'settings.ini'
if not config_path.parent.exists():
config_path.parent.mkdir(parents=True)
24.2 环境适配
平台检测:
python复制import platform
system = platform.system()
if system == 'Windows':
print("Windows系统")
elif system == 'Linux':
print("Linux系统")
25. 代码重构技巧
25.1 函数拆分
长函数重构示例:
python复制# 重构前
def process_data(data):
# 验证数据
if not isinstance(data, list):
raise TypeError("需要列表类型")
if len(data) == 0:
return []
# 处理数据
result = []
for item in data:
if item > 0:
result.append(item * 2)
else:
result.append(abs(item))
# 过滤结果
return [x for x in result if x < 100]
# 重构后
def validate_input(data):
if not isinstance(data, list):
raise TypeError("需要列表类型")
return len(data) > 0
def transform_item(item):
return item * 2 if item > 0 else abs(item)
def process_data(data):
if not validate_input(data):
return []
transformed = [transform_item(item) for item in data]
return [x for x in transformed if x < 100]
25.2 条件简化
多条件重构:
python复制# 重构前
def get_discount_level(orders):
if orders > 100:
return "gold"
elif orders > 50 and orders <= 100:
return "silver"
elif orders > 10 and orders <= 50:
return "bronze"
else:
return "none"
# 重构后
def get_discount_level(orders):
if orders > 100:
return "gold"
if orders > 50:
return "silver"
if orders > 10:
return "bronze"
return "none"
26. 调试技巧进阶
26.1 日志记录
使用logging模块:
python复制import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename='app.log'
)
logger = logging.getLogger(__name__)
def risky_operation(x):
try:
result = 10 / x
logger.info(f"操作成功,结果: {result}")
return result
except ZeroDivisionError:
logger.error("除零错误发生")
raise
26.2 交互式调试
使用IPython嵌入:
python复制from IPython import embed
def complex_calculation(a, b):
# ...中间计算过程
embed() # 在此处进入交互式shell
# ...后续计算
27. 元编程技术
27.1 动态属性
__getattr__使用:
python复制class DynamicAttributes:
def __getattr__(self, name):
if name.startswith('attr_'):
return len(name[5:])
raise AttributeError(f"无属性 {name}")
obj = DynamicAttributes()
print(obj.attr_hello) # 输出5
27.2 类装饰器
修改类行为:
python复制def add_method(cls):
def decorator(func):
setattr(cls, func.__name__, func)
return func
return decorator
@add_method(str)
def double(self):
return self * 2
print("hello".double()) # 输出"hellohello"
28. 多进程编程
28.1 Process类
多进程基础:
python复制from multiprocessing import Process
import os
def worker(name):
print(f"子进程{name} PID: {os.getpid()}")
processes = []
for i in range(3):
p = Process(target=worker, args=(i,))
processes.append(p)
p.start()
for p in processes:
p.join()
28.2 进程池
Pool示例:
python复制from multiprocessing import Pool
def square(x):
return x * x
with Pool(4) as p:
results = p.map(square, range(10))
print(results)
29. 正则表达式
29.1 模式匹配
re模块基础:
python复制import re
text = "联系我: email@example.com 或 电话123-456-7890"
emails = re.findall(r'[\w\.-]+@[\w\.-]+', text)
phones = re.findall(r'\d{3}-\d{3}-\d{4}', text)
29.2 分组提取
命名分组:
python复制pattern = r"(?P<area>\d{3})-(?P<exchange>\d{3})-(?P<line>\d{4})"
match = re.search(pattern, "电话: 123-456-7890")
if match:
print(match.group('area')) # 123
30. 单元测试进阶
30.1 模拟对象
unittest.mock使用:
python复制from unittest.mock import Mock, patch
def get_data():
# 实际会发起网络请求
pass
def test_get_data():
with patch('__main__.get_data') as mock_get:
mock_get.return_value = {'key': 'value'}
result = get_data()
assert result == {'key': 'value'}
30.2 参数化测试
使用pytest.mark.parametrize:
python复制import pytest
@pytest.mark.parametrize("input,expected", [
(3, 9),
(0, 0),
(-2, 4)
])
def test_square(input, expected):
assert input ** 2 == expected
31. 协程深入
31.1 async/await
协程基础:
python复制async def fetch_data():
print("开始获取数据")
await asyncio.sleep(1) # 模拟IO操作
print("数据获取完成")
return {'data': 123}
async def main():
task = asyncio.create_task(fetch_data())
print("主程序继续执行")
result = await task
print(f"获取结果: {result}")
asyncio.run(main())
31.2 协程通信
使用队列:
python复制async def producer(queue):
for i in range(5):
await queue.put(i)
await asyncio.sleep(0.1)
async def consumer(queue):
while True:
item = await queue.get()
print(f"消费: {item}")
queue.task_done()
async def main():
queue = asyncio.Queue()
producers = [asyncio.create_task(producer(queue)) for _ in range(2)]
consumers = [asyncio.create_task(consumer(queue)) for _ in range(3)]
await asyncio.gather(*producers)
await queue.join()
for c in consumers:
c.cancel()
32. 类型系统进阶
32.1 泛型编程
typing.Generic使用:
python复制from typing import TypeVar, Generic, List
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
return self.items.pop()
int_stack = Stack[int]()
int_stack.push(1)
32.2 类型别名
创建复杂类型:
python复制from typing import Dict, List, Tuple
UserId = int
UserName = str
UserData = Tuple[UserId, UserName]
Database = Dict[UserId, UserName]
def process_users(users: List[UserData]) -> Database:
return {uid: name for uid, name in users}
33. 项目实战:Web爬虫
33.1 请求与解析
使用BeautifulSoup:
python复制import requests
from bs4 import BeautifulSoup
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for link in soup.find_all('a'):
print(link.get('href'))
33.2 爬虫框架
Scrapy示例:
python复制import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = ['http://quotes.toscrape.com']
def parse(self, response):
for quote in response.css('div.quote'):
yield {
'text': quote.css('span.text::text').get(),
'author': quote.css('small.author::text').get(),
}
运行爬虫:
bash复制scrapy runspider quotes_spider.py -o quotes.json
