Python : method resolution order of old-style (or

2019-02-14 10:58发布

I have read a lot about Objects in Python Documentation which differentiates these two at some point like:

  • 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.

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()".

1条回答
Melony?
2楼-- · 2019-02-14 11:47

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 of parentclassname.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:

depth first and then left to right

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).

查看更多
登录 后发表回答