0

In Module a.py

class Foo(object):
    def __init__(self):
        self.foo = 20

class Bar(object):
    def __init__(self):
        self.bar = 10

class FooBar(Foo, Bar):
    def __init__(self):
        print "foobar init"
        super(FooBar, self).__init__()
a = FooBar()
print a.foo
print a.bar

In multiple inheritances only first class init method getting called. Is there any way to call all init method in multiple inheritances, so I can access all classes instances variable

Output:

foobar init
20
Traceback (most recent call last):
File "a.py", line 16, in <module>
    print a.bar
AttributeError: 'FooBar' object has no attribute 'bar'

unable to access Bar class variable bar

Kallz
  • 3,244
  • 1
  • 20
  • 38
  • https://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance – RomanPerekhrest Jul 14 '17 at 10:34
  • @Rawing but if only one parent class init need parameter and another parent dosen`t have any parameter than how to use super keyword to call init of all classes – Kallz Jul 14 '17 at 11:48
  • 1
    @Kallz In that case you don't use `super`. You'd do `Foo.__init__(self); Bar.__init__(self, parameter)`. – Aran-Fey Jul 14 '17 at 11:51

1 Answers1

1
class Foo(object):
def __init__(self):
    super(Foo,self).__init__()
    self.foo = 20

class Bar(object):
def __init__(self):
    super(Bar,self).__init__()
    self.bar = 10


class FooBar(Bar,Foo):
def __init__(self):
    print "foobar init"
    super(FooBar,self).__init__()



a = FooBar()
print a.foo
print a.bar

The super() call finds the /next method/ in the MRO(method resolution order) at each step, which is why Foo and Bar have to have it too, otherwise execution stops at the end of Bar.init.

Nandish Patel
  • 116
  • 13
  • What if `Foo`'s `__init__` required a parameter? This code would crash. Using `super` to call an __unknown__ (to `Bar`) constructor is a ___terrible___ idea (unless your classes are _intended_ for diamond inheritance). – Aran-Fey Jul 14 '17 at 11:07
  • i know if Foo's __init__ required a parameter it would crash but here we don't require any parameter and if Foo's __init__ required a parameter i would pass it with super(Bar,self).__init__(PARAMETER). @Rawing – Nandish Patel Jul 14 '17 at 12:58