前言
这里只是简单列出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 算术运算符
2.2 比较运算符
2.3 逻辑运算符
2.4 成员运算符
2.5 身份运算符
2.6 位运算符
三、流程控制
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 condition:
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):
|
4.3 Lambda表达式
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)
|
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 |
十一、最佳实践
- 遵循PEP 8代码风格指南
- 使用虚拟环境管理依赖
- 优先使用with语句管理资源
- 合理使用异常处理
- 编写文档字符串(docstring)
- 使用列表推导式简化代码
- 避免使用全局变量
- 使用类型注解提高可读性
- 编写单元测试保证质量
- 保持代码简洁可读
本文档涵盖Python 3.x主要语法特性,部分高级特性需要特定版本支持。
版权声明: 此文章版权归曦曦所有,如有转载,请注明来自原作者