Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a parent class with another class without keeping the old parent

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.

1 Answers

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
    ...
like image 196
TheEagle Avatar answered Dec 30 '25 08:12

TheEagle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!