本文介绍了Python 中的旧样式和新样式类有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中的旧式和新式类有什么区别?我什么时候应该使用其中一种?

What is the difference between old style and new style classes in Python? When should I use one or the other?

推荐答案

来自 新式和经典类:

在 Python 2.1 之前,旧式类是用户唯一可用的风格.

(旧式)类的概念与类型的概念无关:如果 x 是旧式类的实例,则 x.__class__指定x的类,但type(x)总是.

The concept of (old-style) class is unrelated to the concept of type: if x is an instance of an old-style class, then x.__class__ designates the class of x, but type(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.

在 Python 2.2 中引入了新式类以统一类和类型的概念.新式类只是用户定义的类型,不多也不少.

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.

如果 x 是一个新式类的实例,那么 type(x) 通常是与 x.__class__ 相同(虽然这不能保证 – a允许新式类实例覆盖返回的值对于 x.__class__).

If x is an instance of a new-style class, then type(x) is typically the same as x.__class__ (although this is not guaranteed – a new-style class instance is permitted to override the value returned for x.__class__).

引入新式类的主要动机是提供具有完整元模型的统一对象模型.

它还具有许多直接的好处,例如能够子类化大多数内置类型,或引入描述符",启用计算属性.

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.

出于兼容性原因,默认情况下类仍然是旧样式.

新式类是通过指定另一个新式类来创建的(即类型)作为父类,如果没有,则为顶级类型"对象需要其他父母.

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 只有新式类.

无论是否从 object 子类化,类都是新式的在 Python 3 中.

No matter if you subclass from object or not, classes are new-style in Python 3.

这篇关于Python 中的旧样式和新样式类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 07:24