Why does inheritance in python require that the parent class explicitly inherit the object?

advertisements

Below is two versions of my code:

Non-working one

class A:
    def __init__(self):
        print "I am A "

class B:
    def __init__(self):
        print "I am B "

class C(A, B):
    def __init__(self):
        super(C, self).__init__()

c = C()

This raises exception:

    super(C, self).__init__()
TypeError: must be type, not classobj

Working version

class A(object):
    def __init__(self):
         print "I am A "

class B:
    def __init__(self):
         print "I am B "

class C(A, B):
    def __init__(self):
         super(C, self).__init__()

c = C()

If one of the parent class has inherited object explicitly , there is no exception and things works as desired. Any explanation, why?

With the above working one , it prints "I am A" but not "I am B" which means it initializes only Class A and not Class B. HOw to initialize multiple parent classes in children class?


super() only works for new-style classes(Any class which inherits from object).So You couldn't pass class object to super.

There are two typical use cases for super. In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in other programming languages.

The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that this method have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).

a typical superclass call looks like this:

class C(B):
    def method(self, arg):
        super(C, self).method(arg)