我在外部库中拥有的内容:
# external package content
class Foo:
def func(): ...
class Bar(Foo):
def func():
super().func()
我的代码需要什么:
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()
我需要实现的目标:
Bar
方法,而无需复制/粘贴它们。Bar
必须从我自己的类继承,而不是从另一个类继承。最佳答案
您可以将外部库类中的方法分配给您自己的类,模仿继承(据我所知,这称为猴子修补):
from external_library import Bar as _Bar
class Bar(MyOwnCustomFoo):
func = _Bar.func
...
https://stackoverflow.com/questions/71054325/