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

I read a lot about objects in the Python documentation that distinguish between the two at some point, for example:

  • Old instances, regardless of their class, are implemented using a single built-in type called an instance.
  • A new style class is no more and no less than a custom type.

Can someone explain me more about this "old style (or classic) and new style."

I cannot understand what this line is trying to say:

"For new-style classes, the resolution order of the method is changed dynamically to support super () cumulative calls."

+4
source share
1 answer

Old style 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 have many features using new class styles, for example:

  • super(classname, ...).method() instead of parentclassname.method(...) . The parent method is now defined from the MRO (previously, it was defined by you).
  • __slots__ is a new function that may prevent you from adding dict () to your object and allocate memory only for the attribute in __slots__
  • The python properties ( @property , property() ...) work only with new class styles.

About MRO, check out Python 2.3 Method Resolution Document. Prior to version 2.2, the implementation was as follows:

first and then left to right

while the new C3 is much more complicated, but it handles various cases that the previous one did n’t handle correctly (check the message of Samuele Pedroni on the python mailing list ).

+6
source

Source: https://habr.com/ru/post/1385055/


All Articles