-1

I have a multiple classes in python i.e class a, class b, class c, class d and class d in inheriting the class a,class b, class c and class a, class b, class c having a method m1() then I want to access only the method of class b then how can I access this method?? plz reffer following code.

class a:
       def m1(self):
              print("Class A method m1")

class b:
       def m1(self):
              print("Class B method m1")

class c:
       def m1(self):
              print("Class C method m1")

class d(a,b,c):
       def m2(self):
              print("Class D method m1")
       b().m1()

o1 = d()
o1.m1()
chepner
  • 497,756
  • 71
  • 530
  • 681

1 Answers1

0

There are a few options, all of which may have wider consequences for the rest of your code. You cannot necessarily pick one of the following in a vacuum; you have to consider how your hierarchy as a whole is supposed to work.

  1. Change the inheritance order.

    class d(b, a ,c):  # Put b first
        def m2(self):
            super().m1()  # b.m1 is the first one found
    
  2. Alter the starting point of the search for b.m1

    class d(a, b, c):
        def m2(self):
            # self.__mro__() returns [d, a, b, c]
            super(a, self).m1()  # Start looking after a instead of d
    
  3. Refer directly to the method you want instead of going through the MRO

    class d(a, b, c):
        def m2(self):
            b.m1(self)
    
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Option 3. seems like the cleanest idea. – matszwecja Jul 20 '22 at 13:50
  • (Removed my previous comment, because I'm not sure option 3 is worse than option 2 with regards to the need for a redesign.) – chepner Jul 20 '22 at 13:55
  • I like option 1, because it's explicitly about a `d` instance being more like a `b` instance than an `a` or `c` instance. But if that similarity only relates to the definition of `m1`, then there's definitely a problem with the design of the hierarchy. – chepner Jul 20 '22 at 13:57