问题描述
我已经阅读了很多关于Python文档中的对象,它在某些时候区分了这两个:
- 旧式实例
- 新样式类既不比用户定义的类型更小,也不小于用户定义的类型。
任何人都可以在这个旧样式strong>
我不知道这行是什么意思:
新方法类,方法解析顺序动态更改以支持协作调用super旧类样式:
class BaseClass:
def m1(self):
return 1
class MyClass(BaseClass):
def m1(self):
return BaseClass.m1(self)
新类样式:
class BaseClass(object):
def m1(self):
return 1
类MyClass(BaseClass):
def m1(self):
return super(MyClass,self).m1
使用新的类样式有很多可能性,例如:
-
super(classname,...)。method()
而不是parentclassname.method (...)
。 -
__ slots __
是一个新功能,可以防止在你的对象中添加一个dict()并为__ slots __
- 的属性分配内存。 c> @property ,
property()
...)只适用于新的类样式。 - Old-style instances, independently of their class, are implemented with a single built-in type, called instance.
- A new-style class is neither more nor less than a user-defined type.
关于MRO,请检查文档。 2.2之前,执行方式为:
而新的是C3,更复杂,但处理各种情况,前一个没有正确处理(检查)。
I have read a lot about Objects in Python Documentation which differentiates these two at some point like:
Could anyone explain to me more on this "old-style (or classic) and new-style."
I can not figure out what this line is trying to say :
"For new-style classes, the method resolution order changes dynamically to support cooperative calls to super()".
Old class style:
class BaseClass:
def m1(self):
return 1
class MyClass(BaseClass):
def m1(self):
return BaseClass.m1(self)
New class style:
class BaseClass(object):
def m1(self):
return 1
class MyClass(BaseClass):
def m1(self):
return super(MyClass, self).m1()
They are a lot of possibilities using new classes styles, like:
super(classname, ...).method()
instead ofparentclassname.method(...)
. The parent method is now determined from MRO (before, it was determined by you).__slots__
is a new feature that can prevent to add a dict() in your object and allocate the memory only for the attribute in__slots__
- python properties (
@property
,property()
...) is working only on new classes styles.
About MRO, check the document The Python 2.3 Method Resolution Order. Before 2.2, the implementation was:
while the new one is C3, much more complicated but handle various case that the previous one didn't handle correctly (check the Samuele Pedroni post on the python mailing list).
这篇关于Python:旧样式(或经典)和新样式对象的方法解析顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!