0

Consider:

   class Base():
      def foo():
          ...

   class A(Base):
      def bar():
          ...

   class MyBase(Base):
      def zee():
          ...
      def bar():
          ...


  class MyA(MyBase, A):
       def zee():
          ...

Now I want to introduce MyA class which has the property of both MyBase and also A. Is the way I inroduced MyA correct?

Base ___
 |      Possible other ancestors
 |      |
MyBase  A
 |      |
 MyA-----

Note both MyBase and A are derived from Base, So it refers to Base from different paths. I would like to know if there is any considerations or alternative approaches.

For example while bar is introduced in A and also MyBase, if I don't have a bar in MyA, the bar of Mybase is considered the overridden method of A for MyA?!! How could I avoid it? unless I change MyBase method name.

Ahmad
  • 8,811
  • 11
  • 76
  • 141
  • This is a big topic. I suggest searching for Python multiple inheritance and reading up on it. In your example, there are no conflicts so it's very simple. In practice, conflicts do occur, particularly with `__init__`. In general, you want to call the `__init__` method in your base classes from the `__init__` method in the derived class. But there may be more than one. You can use `super()` to help with it. – Tom Karzes Aug 20 '22 at 04:13
  • If you really want to understand how Python resolves conflicts, you need to read about Python's [Method Resolution Order](https://www.python.org/download/releases/2.3/mro/), as described in the preceding link. – Tom Karzes Aug 20 '22 at 04:15
  • @TomKarzes Thanks, I also modified it a bit to show some conflicts, like `bar` method, which is both in `MyBase` and `A` wondering which is overrided. – Ahmad Aug 20 '22 at 05:04
  • 1
    Does this answer your question? [What does "mro()" do?](https://stackoverflow.com/questions/2010692/what-does-mro-do) – Tom Karzes Aug 20 '22 at 05:16
  • @TomKarzes I added a specific problem I encountered now after introducing my classes as above. – Ahmad Aug 20 '22 at 06:12
  • The example keeps changing, which is usually a good indication that the question should be closed. It's a duplicate, and you have a complete answer in the link I provided. I know it's a bit complicated, but a simpler explanation will be wrong, or at best incomplete. If you don't want to understand it, then just avoid multiple inheritance. – Tom Karzes Aug 20 '22 at 07:12
  • Okay, no problem, however I read the link to some extent and I underestand to some extent, just wanted to assure the whole approuche is good and there isn't other alternative. Also, as you see, I can't avoid multiple inheritance unless I repeat code. – Ahmad Aug 20 '22 at 08:31
  • Take a look at the duplicate SO question link. One of the answers shows how to actually inspect the mro for a given class. – Tom Karzes Aug 20 '22 at 08:36

0 Answers0