What is the difference between old style and new style classes in Python?(Python中的旧样式类和新样式类有什么区别?)
问题描述
What is the difference between old style and new style classes in Python? When should I use one or the other?
From New-style and classic classes:
Up to Python 2.1, old-style classes were the only flavour available to the user.
The concept of (old-style) class is unrelated to the concept of type: if
x
is an instance of an old-style class, thenx.__class__
designates the class ofx
, buttype(x)
is always<type 'instance'>
.This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance.
New-style classes were introduced in Python 2.2 to unify the concepts of class and type. A new-style class is simply a user-defined type, no more, no less.
If x is an instance of a new-style class, then
type(x)
is typically the same asx.__class__
(although this is not guaranteed – a new-style class instance is permitted to override the value returned forx.__class__
).The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model.
It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of "descriptors", which enable computed properties.
For compatibility reasons, classes are still old-style by default.
New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the "top-level type" object if no other parent is needed.
The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns.
Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are "fixes" that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.
Python 3 only has new-style classes.
No matter if you subclass from
object
or not, classes are new-style in Python 3.
这篇关于Python中的旧样式类和新样式类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python中的旧样式类和新样式类有什么区别?
基础教程推荐
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01