前言

这里只是简单列出python 3语言的知识点


一、基础语法

1.1 程序结构

1
2
3
4
5
6
7
# 单行注释
"""
多行注释/文档字符串
"""

if __name__ == '__main__': # 主程序入口
print("Hello World!") # 输出语句

1.2 变量与数据类型

类型 说明 示例
int 整数 num = 10
float 浮点数 pi = 3.14
bool 布尔值 flag = True
str 字符串 s = "Python"
list 列表 lst = [1, 2, 3]
tuple 元组 tup = (1, 2, 3)
set 集合 s = {1, 2, 3}
dict 字典 d = {'a': 1, 'b': 2}

1.3 动态类型特性

1
2
3
var = 10        # 整数
var = "Python" # 字符串
var = [1, 2, 3] # 列表

二、运算符

2.1 算术运算符

1
+ - * / // % **

2.2 比较运算符

1
== != > < >= <=

2.3 逻辑运算符

1
and or not

2.4 成员运算符

1
in not in

2.5 身份运算符

1
is is not

2.6 位运算符

1
& | ^ ~ << >>

三、流程控制

3.1 条件语句

1
2
3
4
5
6
if condition1:
# ...
elif condition2:
# ...
else:
# ...

3.2 循环结构

1
2
3
4
5
6
7
8
9
10
11
# while循环
while condition:
# ...

# for循环
for item in sequence:
# ...

# 循环控制
break # 终止循环
continue # 跳过本次迭代

3.3 异常处理

1
2
3
4
5
6
try:
# 可能出错的代码
except ValueError as e:
# 异常处理
finally:
# 最终执行

四、函数

4.1 函数定义

1
2
3
4
def func(arg1, arg2=default):
"""文档字符串"""
# 函数体
return result

4.2 参数类型

1
2
3
4
5
6
7
8
9
# 位置参数
func(a, b)

# 关键字参数
func(arg1=value1, arg2=value2)

# 可变参数
def func(*args, **kwargs):
# args是元组,kwargs是字典

4.3 Lambda表达式

1
square = lambda x: x**2

4.4 装饰器

1
2
3
4
5
6
7
8
9
def decorator(func):
def wrapper(*args, **kwargs):
# 装饰逻辑
return func(*args, **kwargs)
return wrapper

@decorator
def func():
# ...

五、数据结构

5.1 列表操作

1
2
3
4
lst = [1, 2, 3]
lst.append(4) # 添加元素
lst[1:3] # 切片
[x**2 for x in lst] # 列表推导式

5.2 字典操作

1
2
3
4
d = {'a': 1, 'b': 2}
d['c'] = 3 # 添加键值对
d.get('a') # 安全获取
{k: v for k, v in d.items() if v > 1} # 字典推导式

5.3 集合操作

1
2
3
4
s = {1, 2, 3}
s.add(4) # 添加元素
s1 | s2 # 并集
s1 & s2 # 交集

六、面向对象编程

6.1 类与对象

1
2
3
4
5
6
7
8
9
10
11
class MyClass:
# 类属性
class_attr = 0

def __init__(self, attr):
# 实例属性
self.attr = attr

def method(self):
# 实例方法
return self.attr

6.2 继承与多态

1
2
3
4
5
6
7
class Child(Parent):
def __init__(self, attr):
super().__init__(attr)

def method(self):
# 方法重写
return super().method() * 2

6.3 特殊方法

1
2
3
4
5
6
class Vector:
def __add__(self, other): # 运算符重载
return Vector(self.x + other.x)

def __str__(self): # 字符串表示
return f"Vector({self.x})"

七、模块与包

7.1 模块导入

1
2
3
4
import module
from module import func
import module as alias
from package.submodule import Class

7.2 创建包

1
2
3
4
my_package/
__init__.py
module1.py
module2.py

八、文件操作

8.1 文件读写

1
2
3
4
5
with open('file.txt', 'r') as f:
content = f.read()

with open('file.txt', 'w') as f:
f.write("New content")

8.2 常见模式

1
2
3
4
5
'r'   # 读取(默认)
'w' # 写入(覆盖)
'a' # 追加
'r+' # 读写
'b' # 二进制模式

九、高级特性

9.1 生成器

1
2
3
4
5
6
def gen():
yield 1
yield 2

g = gen()
next(g) # 返回1

9.2 上下文管理器

1
2
3
4
5
6
7
8
class MyContext:
def __enter__(self):
# 进入上下文
return self

def __exit__(self, exc_type, exc_val, exc_tb):
# 退出上下文
pass

9.3 类型注解(Python 3.5+)

1
2
def func(name: str, age: int) -> str:
return f"{name} is {age} years old"

十、标准库常用模块

模块 用途
os 操作系统接口
sys 系统相关参数
math 数学运算
datetime 日期时间
json JSON处理
re 正则表达式
collections 扩展容器
itertools 迭代工具
multiprocessing 多进程
threading 多线程
asyncio 异步IO

十一、最佳实践

  1. 遵循PEP 8代码风格指南
  2. 使用虚拟环境管理依赖
  3. 优先使用with语句管理资源
  4. 合理使用异常处理
  5. 编写文档字符串(docstring)
  6. 使用列表推导式简化代码
  7. 避免使用全局变量
  8. 使用类型注解提高可读性
  9. 编写单元测试保证质量
  10. 保持代码简洁可读
    本文档涵盖Python 3.x主要语法特性,部分高级特性需要特定版本支持。