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?

3
  • Your two base classes both have a class attribute and an instance attribute with the same name—which is just asking for trouble. Commented Oct 24, 2018 at 1:01
  • @Martineau. Exacerbated by the fact that OP isn't using parent constructors properly. Commented Oct 24, 2018 at 1:15
  • Actually, I was looking for the correct syntax to invoke the base class constructors. Commented Oct 24, 2018 at 1:25

1 Answer 1

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, that's what I was looking for. Tried using super().__init__(), but couldn't get the required results.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.