3

What I have in an external library:

# external package content


class Foo:
    
    def func(): ...


class Bar(Foo):
    
    def func():
        super().func()

What I need in my code:

from external_library import Bar

class MyOwnCustomFoo:

    def func(): ...


# Do some magic here to replace a parent class with another class without keeping the old parent


# Class name can be not 'Bar', but the class must have all 'Bar' attributes
class Bar(MyOwnCustomFoo):

    def func():
        super().func()

Goals I need to achieve:

  1. I must have all Bar methods without copy/pasting them.
  2. Bar must inherit from my own class, not from another one.
Nairum
  • 547
  • 6
  • 21
  • 2
    What you want is not possible, not even with metaclasses. Maybe someone might find a hack with dirty monkey-patching to do this, that I cannot come up with right now. But this whole idea is a non-starter. I think that you might have an architectual problem that might be solved in another way. To address this, we'd need some background on the issue you're trying to solve. – Richard Neumann Feb 09 '22 at 17:50
  • 1
    Just because you want a class that's like `Bar`, but inheriting from `MyOwnCustomFoo` instead, does not mean you should actually change `Bar`. Assume that classes are defined the way they are for a reason. Classes are not infinitely malleable. – chepner Feb 09 '22 at 17:53

2 Answers2

1

You could assign the methods from the external library class to your own class, mimicking inheritance (AFAIK this is called monkey-patching):

from external_library import Bar as _Bar

class Bar(MyOwnCustomFoo):
    func = _Bar.func
    ...
Programmer
  • 5,276
  • 3
  • 9
  • 33
-3

You need to use what's called a "monkey patch" to override the bar.foo()in the imported instance of the class. This link has a sufficient example:

See Monkey Patching in Python (Dynamic Behavior) - GeeksforGeeks

martineau
  • 112,593
  • 23
  • 157
  • 280
  • In order to be immediately helpful to readers (and avoid [link-rot](http://en.wikipedia.org/wiki/Link-rot)), answers that provide at least a summary of the solution directly are preferred, with links used to offer additional information. – martineau Feb 09 '22 at 17:56