Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I am currently working on some methods that are resolved in classic resolution order and I wanted to know how is it different from the new order?

I tried the same example by writing the example in a new style but the result is no different than what was obtained with old-style classes. The python version I am using to run the sample is 2.5.2. Below is the sample code:

class Base1(object):  

    def amethod(self): print "Base1"  

class Base2(Base1):  

    pass

class Base3(object):  

    def amethod(self): print "Base3"

class Derived(Base2,Base3):  

    pass

instance = Derived()  

instance.amethod()  

print Derived.__mro__  

The call instance.amethod() prints Base1, but as per my understanding of the MRO with the new style of classes, the output should have been Base3. The call Derived.__mro__ prints:

(<class '__main__.Derived'>, <class '__main__.Base2'>, <class '__main__.Base1'>, <class '__main__.Base3'>, <type 'object'>)

1 Answer

0 votes
by (108k points)

The basic distinction between resolution order for legacy vs new-style classes comes when the same parent class occurs more than once in the "naive", depth-first approach -- e.g., consider a "diamond inheritance" case:

>>> class A: x = 'a'

... 

>>> class B(A): pass

... 

>>> class C(A): x = 'c'

... 

>>> class D(B, C): pass

... 

>>> D.x

'a'

In the above code, legacy-style, the resolution order is D - B - A - C - A: so when viewing up D.x, A is the first base in resolution order to explain it, thereby hiding the definition in C. While:

>>> class A(object): x = 'a'

... 

>>> class B(A): pass

... 

>>> class C(A): x = 'c'

... 

>>> class D(B, C): pass

... 

>>> D.x

'c'

>>> 

#here, new-style, the order is:

>>> D.__mro__

(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, 

    <class '__main__.A'>, <type 'object'>)

with A forced to come in resolution order only once and after all of its subclasses, so that overrides actually work normally.

Are you interested to learn Python in detail? Sign up for this perfect Python Training course by Intellipaat.

Browse Categories

...