简体   繁体   中英

Python : method resolution order of old-style (or classic) and new-style objects

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM