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

问题描述

Python中的旧样式和新样式类有什么区别?现在是否有理由使用旧式类?

What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days?

推荐答案

从:

在Python 2.2中引入了新式类来统一类和类型的概念。一个新式的类只是一个用户定义的类型,没有更多,没有更少。如果x是新式类的实例,则 type(x)通常与 x .__ class相同(虽然这不能保证 - 一个新式的类实例允许覆盖 x .__ class __ )返回的值。

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 as x.__class__ (although this is not guaranteed – a new-style class instance is permitted to override the value returned for x.__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只有新式样的类。无论是否从 object 子类化,类在Python 3中都是新式的。然而,建议您仍然从 object

Python 3 only has new-style classes. No matter if you subclass from object or not, classes are new-style in Python 3. It is however recommended that you still subclass from object.

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

07-05 07:24