2

EDIT: Thanks for the information about the class attributes. I understand these are similar to static in other OO languages. Now in the following code, I wish to use the __init__ of the base classes to set x and y in the derived class. Any guidance would be appreciated.

class Base1:
  def __init__(self, x):
      self.x = x

class Base2:
  def __init__(self, y):
      self.y = y

class Derv (Base1, Base2):
  def __init__(self, x, y):
      self.x = x
      self.y = y

OLD:

Related to Multiple inheritance: The derived class gets attributes from one base class only?

Now, what is happening in the following example (dictionary of d is empty):

class Base1:
  x = 10

class Base2:
  y = 10

class Derv (Base1, Base2):
  pass


d=Derv()
print (d.__dict__)

Although this works when we change the code to following:

class Base1:
  x = 0
  def __init__(self, x):
      self.x = x

class Base2:
  y = 0
  def __init__(self, y):
      self.y = y

class Derv (Base1, Base2):
  def __init__(self, x, y):
      self.x = x
      self.y = y

I think this is more because of defining x and y in the __init__ method of Derv. But, if I wish to set the values using base class constructors, what is the correct way?

Yelena
  • 423
  • 3
  • 14

1 Answers1

2

Easiest and best: just call the initializers in each base!

class Derv(Base1, Base2):
    def __init__(self, x, y):
        Base1.__init__(self, x)
        Base2.__init__(self, y)
wim
  • 338,267
  • 99
  • 616
  • 750
  • Thank you so much, that's what I was looking for. Tried using super().__init__(), but couldn't get the required results. – Yelena Oct 24 '18 at 01:23