Python中的旧样式类和新样式类有什么区别?
时间:2020-03-05 18:50:57 来源:igfitidea点击:
Python中的旧样式类和新样式类有什么区别?这些天是否有理由使用老式类?
解决方案
回答
从http://docs.python.org/2/reference/datamodel.html#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, 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. 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 only has new-style classes. No matter if you subclass from object or not, classes are new-style in Python 3.
回答
确切地说,除非代码需要与2.2之前的Python版本一起使用,否则应始终使用新型类。
回答
新型类继承自object,并且必须在Python 2.2及更高版本中这样编写(即,class Classname(object):而不是class Classname:)。核心更改是统一类型和类,这样做的好处是它允许我们从内置类型继承。
阅读descrintro以获得更多详细信息。
回答
声明方式:
新样式类从对象或者另一个新样式类继承。
class NewStyleClass(object): pass class AnotherNewStyleClass(NewStyleClass): pass
老式的类则没有。
class OldStyleClass(): pass
回答
旧样式的类仍然比属性查找要快一些。这通常并不重要,但是在对性能敏感的Python 2.x代码中可能有用:
In [3]: class A: ...: def __init__(self): ...: self.a = 'hi there' ...: In [4]: class B(object): ...: def __init__(self): ...: self.a = 'hi there' ...: In [6]: aobj = A() In [7]: bobj = B() In [8]: %timeit aobj.a 10000000 loops, best of 3: 78.7 ns per loop In [10]: %timeit bobj.a 10000000 loops, best of 3: 86.9 ns per loop