0

Say I have following

Class A(object):
    base Functions

Class B (A):
   some useful functions

Class C(object)
    req base functions

Now I want to create a class which has all the functions from B but instead of functions from A refers to functions from C. Something like

Class D(B,C)
   and when B calls super it should look in C instead of A

The way that I am achieving it now is copy pasting the whole class B and just inheriting from C instead of A. Is there a better way to solve this problem?

Composition can surely solve the problem, but Class B is already in heavy use so I don't want to change it.

Andy
  • 49,085
  • 60
  • 166
  • 233
  • Pretty sure this is what you are looking for http://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance . If not could you specify how is it different? – Tomasz Plaskota Jul 15 '16 at 14:01

1 Answers1

1

Change the __bases__ attribute of B class.

Well, it's ugly but it works:

class A(object):
    def f(self):
        print("A.f()")

class B (A):
    def g(self):
        print("B.g()", end=": ")
        super(B, self).f()

class C(object):
    def f(self):
        print("C.f()")


B.__bases__ = (C,)
b = B()
b.g()

You get:

B.g(): C.f()

You can use fudge.patch to do it during your unit test.

Note that your question is a duplicate of How to dynamically change base class of instances at runtime?

Community
  • 1
  • 1
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
  • Thanks Laurent. I was unaware of that functionality. But I want to create a new class D which is exactly like B only inherits from C. I don't want to change the base of B itself. The objects of B should not see any change. – Kedar Jathar Jul 18 '16 at 05:05