Python 学习指南
目录
基础语法
数据类型
python
# 基本类型
number = 42 # 整数
float_num = 3.14 # 浮点数
string = "Hello" # 字符串
boolean = True # 布尔值
none = None # 空值
# 容器类型
list_data = [1, 2, 3] # 列表
tuple_data = (1, 2, 3) # 元组
dict_data = {"key": "value"} # 字典
set_data = {1, 2, 3} # 集合
# 类型转换
str_num = str(42)
int_str = int("42")
float_str = float("3.14")说明:
- 基本数据类型
- 容器类型
- 类型转换
- 类型检查
控制流程
python
# 条件语句
if age >= 18:
print("成年人")
elif age >= 12:
print("青少年")
else:
print("儿童")
# 循环语句
for i in range(5):
print(i)
while count > 0:
print(count)
count -= 1
# 列表推导式
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]说明:
- 条件语句
- 循环语句
- 列表推导式
- 生成器表达式
函数
python
# 函数定义
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# 参数类型
def process_data(data: list, count: int = 0) -> str:
return f"处理了 {count} 条数据"
# 可变参数
def sum_numbers(*args):
return sum(args)
# 关键字参数
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
# Lambda 函数
square = lambda x: x**2说明:
- 函数定义
- 参数类型
- 可变参数
- Lambda 函数
模块
python
# 模块导入
import math
from datetime import datetime
import numpy as np
# 自定义模块
# mymodule.py
def hello():
print("Hello from mymodule")
# 使用模块
import mymodule
mymodule.hello()
# 包结构
# mypackage/
# __init__.py
# module1.py
# module2.py说明:
- 模块导入
- 自定义模块
- 包结构
- 模块搜索
面向对象
类与对象
python
# 类定义
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print(f"Hello, I'm {self.name}")
# 创建对象
person = Person("John", 25)
person.say_hello()
# 属性访问
print(person.name)
person.age = 26说明:
- 类定义
- 对象创建
- 属性访问
- 方法调用
继承与多态
python
# 继承
class Student(Person):
def __init__(self, name, age, school):
super().__init__(name, age)
self.school = school
def study(self):
print(f"{self.name} is studying at {self.school}")
# 多态
def introduce(person):
person.say_hello()
student = Student("Alice", 20, "University")
introduce(student)说明:
- 继承
- 多态
- 方法重写
- 父类调用
装饰器
python
# 函数装饰器
def log(func):
def wrapper(*args, **kwargs):
print(f"调用函数: {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log
def add(a, b):
return a + b
# 类装饰器
class Singleton:
def __init__(self, cls):
self.cls = cls
self.instance = None
def __call__(self, *args, **kwargs):
if not self.instance:
self.instance = self.cls(*args, **kwargs)
return self.instance
@Singleton
class Database:
pass说明:
- 函数装饰器
- 类装饰器
- 装饰器链
- 参数化装饰器
元类
python
# 元类定义
class MetaClass(type):
def __new__(cls, name, bases, attrs):
# 修改类属性
attrs['version'] = '1.0'
return super().__new__(cls, name, bases, attrs)
# 使用元类
class MyClass(metaclass=MetaClass):
pass
print(MyClass.version)说明:
- 元类定义
- 类创建过程
- 属性修改
- 元类应用
高级特性
迭代器
python
# 迭代器协议
class CountDown:
def __init__(self, start):
self.start = start
def __iter__(self):
return self
def __next__(self):
if self.start <= 0:
raise StopIteration
self.start -= 1
return self.start
# 使用迭代器
for i in CountDown(5):
print(i)说明:
- 迭代器协议
- 迭代器实现
- 迭代器使用
- 内置迭代器
生成器
python
# 生成器函数
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# 生成器表达式
squares = (x**2 for x in range(10))
# 使用生成器
for num in fibonacci(5):
print(num)说明:
- 生成器函数
- 生成器表达式
- yield 语句
- 生成器应用
上下文管理器
python
# 上下文管理器
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
# 使用上下文管理器
with FileManager("test.txt", "w") as f:
f.write("Hello, World!")说明:
- 上下文管理器
- with 语句
- 资源管理
- 异常处理
异步编程
python
# 异步函数
async def fetch_data(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
# 异步主函数
async def main():
tasks = [
fetch_data("http://api1.example.com"),
fetch_data("http://api2.example.com")
]
results = await asyncio.gather(*tasks)
return results
# 运行异步程序
asyncio.run(main())说明:
- 异步函数
- 异步上下文
- 任务管理
- 并发控制
标准库
文件操作
python
# 文件读写
with open("file.txt", "r") as f:
content = f.read()
with open("file.txt", "w") as f:
f.write("Hello, World!")
# 文件操作
import os
os.path.exists("file.txt")
os.makedirs("new_dir")
os.remove("file.txt")说明:
- 文件读写
- 文件操作
- 路径处理
- 目录管理
网络编程
python
# HTTP 请求
import requests
response = requests.get("http://api.example.com")
data = response.json()
# Socket 编程
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(("localhost", 8080))
s.sendall(b"Hello, World!")
data = s.recv(1024)说明:
- HTTP 请求
- Socket 编程
- 网络协议
- 并发处理
并发编程
python
# 多线程
import threading
def worker():
print("Worker thread")
thread = threading.Thread(target=worker)
thread.start()
# 多进程
import multiprocessing
def process_worker():
print("Process worker")
process = multiprocessing.Process(target=process_worker)
process.start()说明:
- 多线程
- 多进程
- 线程同步
- 进程通信
数据处理
python
# 数据处理
import pandas as pd
df = pd.DataFrame({
"name": ["John", "Alice"],
"age": [25, 30]
})
# 数据可视化
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 2, 3])
plt.show()说明:
- 数据处理
- 数据可视化
- 数据分析
- 数据存储
最佳实践
1. 代码规范
- 遵循 PEP 8
- 使用类型注解
- 编写文档字符串
- 代码审查
2. 性能优化
- 使用生成器
- 避免全局变量
- 使用内置函数
- 内存管理
3. 安全实践
- 输入验证
- 异常处理
- 资源管理
- 安全配置
学习资源
官方文档
视频课程
- 慕课网
- 极客时间
- B站技术区
- YouTube 技术频道
工具推荐
本文档持续完善中,欢迎补充与建议!