首页 新闻 会员 周边 捐助

类属性/方法共享,实例属离 —— 这是 Python 对象模型的设计初衷

0
[已关闭问题] 关闭于 2025-09-07 23:23

类属性/方法共享,实例属离 —— 这是 Python 对象模型的设计初衷。真的吗,对吗,官网有说吗

1. 实例属性只存在于该实例的 __dict__(或 __slots__),类字典里永远看不到


官方 tutorial 3.11 §9.4
“Each instance has its own namespace (its __dict__), which is independent of the class namespace.”
翻译:每个实例有自己的命名空间(`dict),跟类的命名空间互不干扰。

 

1. 实例属性只存在于该实例的 __dict__(或 __slots__),类字典里永远看不到

类属性位于 class namespace,被所有实例共享


官方 tutorial 同一节
“Class attributes are shared by all instances of the class.”
紧接着还给了一个计数器的例子,演示所有实例看到的 Counter.count 是同一数字。


3. 方法本质上也是类属性,因而通过继承被全部子类共享

_java_python的主页 _java_python | 小虾三级 | 园豆:984
提问于:2025-09-07 23:22
< >
分享
所有回答(1)
0

Language Reference §3.3.2
“Functions defined in a class become methods when the class is instantiated and are accessed through the instance. … The function object is looked up in the class’s namespace.”
也就是说 b.add() 先找到 B.__mro__ 里的 add 函数,再把它绑成方法;函数本体只有一份,靠描述器协议把 self 设成当前实例。


4. 属性查找顺序(因此出现“子类实例能读到父类 方法 里绑的 self.x”)被正式写成 MRO


Language Reference §3.3.3
“Attribute references are resolved by searching the namespace of the class and its base classes according to the method resolution order.”
这就是“方法共享”的算法化描述。

_java_python | 园豆:984 (小虾三级) | 2025-09-07 23:23
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册