Pranav Arora
Pranav Arora

Reputation: 33

How does python 2 and 3 deal with inheritance differently?

Why is the code output is different in python 2 and python 3?

class A:
    def m(self):
        print("m of A called")

class B(A):
    pass

class C(A):
    def m(self):
        print("m of C called")

class D(B,C):
    pass

x = D()
x.m()

Actual Output:

$ python  diamond1.py     //python 2 used for the code 
m of A called

$ python3 diamond1.py     //python 3 used for the code
m of C called

Can somebody tell how(the order of calling) are the methods (method m) being called and why and what is the difference in their implementation in python 2 and python 3?

Upvotes: 2

Views: 265

Answers (1)

NPE
NPE

Reputation: 500683

The difference is specific to Python 2 and has to do with old-style vs new-style classes (Python 3 only has the latter). In particular, the two styles of classes use different method resolution orders.

For more information, see https://wiki.python.org/moin/NewClassVsClassicClass

If you change the code like so:

class A(object):

you'll get consistent behaviour as it'll make everything a new-style class.

Old-style classes only exist for compatibility with Python 2.1 and earlier (we're talking the year 2001).

Upvotes: 2

Related Questions