面向对象
面向对象编程(OOP)通过类和对象组织代码。类是模板,对象是模板的实例。
核心概念
- 类 class:
class 类名:定义; - 属性:对象的数据;
- 方法:对象的行为,第一个参数是 self;
- __init__:构造方法,创建对象时自动调用;
- 继承:子类复用父类代码;
- 封装:私有属性
_name(约定); - 多态:不同对象对同一方法有不同实现。
代码示例
# 定义类
class Student:
school = "CodeCourse" # 类属性
def __init__(self, name, score): # 构造方法
self.name = name # 实例属性
self.score = score
def describe(self): # 实例方法
return f"{self.name} 的分数是 {self.score}"
@classmethod
def info(cls):
return f"学校:{cls.school}"
# 创建对象
s1 = Student("小王", 92)
s2 = Student("小李", 88)
print(s1.describe()) # 小王 的分数是 92
print(Student.info()) # 学校:CodeCourse
# 继承
class VipStudent(Student):
def __init__(self, name, score, level):
super().__init__(name, score)
self.level = level
def describe(self): # 方法重写(多态)
return f"{self.name}(VIP{self.level})分数 {self.score}"
vip = VipStudent("小张", 95, 2)
print(vip.describe()) # 小张(VIP2)分数 95
📚 Python 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
print("hello") | 输出到控制台 |
name = "张三" | 变量赋值(无需声明类型) |
if x > 0: ... | 条件判断(注意冒号和缩进) |
for i in range(10): ... | 循环(缩进是语法的一部分) |
while x < 10: ... | 条件循环 |
def fn(a, b): return a + b | 定义函数 |
class Person: ... | 定义类 |
list = [1, 2, 3] | 列表(可改) |
tuple = (1, 2) | 元组(不可改) |
dict = {"key": "value"} | 字典(键值对) |
set = {1, 2, 3} | 集合(去重) |
len(obj) | 取长度 |
str(x) / int(x) / float(x) | 类型转换 |
s.split(",") | 字符串按分隔符拆分 |
" ".join(list) | 列表拼接成字符串 |
import os | 导入模块 |
from math import sqrt | 从模块导入指定函数 |
try: ... except Exception as e: ... | 异常捕获 |
with open("a.txt", "r") as f: ... | 文件读取(自动关闭) |
f"你好 {name}" | f-string 格式化 |
lambda x: x * 2 | 匿名函数 |
list(map(fn, arr)) | 函数式处理列表 |
range(start, stop, step) | 生成数字序列 |
if __name__ == "__main__": | 主入口判断 |
pip install 包名 | 安装第三方包(命令行) |