Python对象生成的设计哲学
已于 2025年12月18日 16:19 修改
访问次数:0
Python 中「实例」与「类」的整体统一模型
一、一句话总览(先给你结论)
在 Python 中:
- 实例是对象
- 类也是对象
- 实例由类创建
- 类由元类(通常是 type)创建
- object 定义“存在”,type 定义“构造”
二、三层对象世界(这是所有理解的根)
Python 的对象体系只有 三层,没有第四层。
| 层级 | 名称 | 例子 | __class__ |
|---|---|---|---|
| 第 1 层 | 实例对象 | stu = Student() | Student |
| 第 2 层 | 类对象 | Student | type |
| 第 3 层 | 元类对象 | type | type |
📌 object 是根基类,不是层级
三、实例(instance)是什么?
1️⃣ 实例的定义
实例是类的具体存在
stu = Student("Tom", 18)本质是:
stu = Student.__call__()
2️⃣ 实例创建流程(精确版)
Student.__call__()│├─ Student.__new__(Student)│ → 分配内存,返回实例│├─ Student.__init__(instance)│ → 初始化属性│└─ 返回 instance📌 关键点:
- __new__ 创建对象
- __init__ 初始化对象
- 实例的 __class__ 指向类对象
stu.__class__ is Student
四、类(class)是什么?
1️⃣ 类不是“语法”,而是对象
class Student: x = 1这不是声明,而是 运行时执行的代码块。
2️⃣ 类创建流程(由 metaclass 驱动)
执行 class 语句│├─ ① 解析类名、父类、metaclass├─ ② metaclass.__prepare__()│ → 创建 namespace├─ ③ 执行 class body│ → 填充 namespace(x = 1, def ...)├─ ④ metaclass.__new__(cls, name, bases, namespace)│ → 创建类对象├─ ⑤ metaclass.__init__()│└─ 得到类对象 Student📌 默认:
Student.__class__ is type
五、instance / class / metaclass 的关系一图流
type ▲ │ (实例关系) Student ▲ │ stu = Student()继承关系:Student ───► objecttype ───► object
六、object 和 type 的分工哲学(你已经理解,但要定型)
object:存在的底座
- 所有实例最终继承 object
- 提供最基础的对象语义
- 不关心“怎么创建”
object.__bases__ == ()
type:构造的统一者
- 所有类都是 type 的实例
- 负责:namespace → 类对象bases → MRO
- 自举闭环:type.__class__ is type
七、class 与 bases 的根本区别(核心常考混淆点)
| 属性 | 含义 |
|---|---|
__class__ | “我是谁的实例” |
__bases__ | “我继承了谁” |
stu.__class__ == StudentStudent.__class__ == typeStudent.__bases__ == (object,)type.__bases__ == (object,)📌 实例关系 ≠ 继承关系
八、方法、属性、绑定的本质(顺带总结)
1️⃣ 方法不是“属于实例的”
stu.say_hello= 函数 + 实例绑定
Student.say_hello → descriptor → bound method
2️⃣ 属性查找顺序(实例 → 类 → 父类)
stu.__dict__→ Student.__dict__→ object.__dict__
九、为什么 Python 这样设计?(设计哲学一句话版)
Python 选择把“类”也当作对象, 以换取极致的动态性与反射能力, 并用 type / object 的最小闭环保证系统自洽。
这直接催生了:
- Django ORM
- dataclass
- attrs / pydantic
- 动态代理 / 装饰器
十、你现在可以牢牢记住的“终极模型”
实例是“被创建的对象”, 类是“创建实例的对象”, 元类是“创建类的对象”, object 定义存在,type 定义构造。
评论(0)