2

I have a class that inherits from two other classes, so:

# library_file.py

from foo import A, B

class Base(A, B):
      ...

...elsewhere I have a subclass that inherits from this Base class...

# my_file.py

from bar import C

from library_file import Base

class MyClass(Base):
      .....

I would like Base to actually inherit C rather than B without hacking the original file (library_file.py). Is there any way of approaching this?

OAFC
  • 53
  • 4
  • Possible duplicate of https://stackoverflow.com/questions/9539052/how-to-dynamically-change-base-class-of-instances-at-runtime – Luv Apr 29 '20 at 11:38

1 Answers1

2

Since B is defined in foo rather than in the same file as Base, you can patch foo.B with bar.C first before importing Base:

from unittest.mock import patch
from bar import C

with patch('foo.B', C):
    from library_file import Base

print(Base.__bases__)

This outputs:

(<class 'foo.A'>, <class 'bar.C'>)

Demo: https://repl.it/@blhsing/KindLovingInfo

blhsing
  • 91,368
  • 6
  • 71
  • 106