python - 在不保留旧父类的情况下用另一个类替换父类

我在外部库中拥有的内容:

# 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()

我需要实现的目标:

  1. 我必须拥有所有 Bar 方法,而无需复制/粘贴它们。
  2. Bar 必须从我自己的类继承,而不是从另一个类继承。

最佳答案

您可以将外部库类中的方法分配给您自己的类,模仿继承(据我所知,这称为猴子修补):

from external_library import Bar as _Bar

class Bar(MyOwnCustomFoo):
    func = _Bar.func
    ...

https://stackoverflow.com/questions/71054325/

相关文章:

css - 使用 CSS 模块时从父项覆盖样式的 'correct' 方法是什么?

react-native - appcenter codepush 更新 Android 但不更新

c# - Asp.net 长时间运行的后台任务。最佳实践?

mysql - Prisma - 唯一约束失败,而架构中没有唯一字段

java - 如何使用 vagrant 在 ubuntu 上安装 maven 3.8 和 jdk 1

firebase - 为什么 Firebase 动态链接总是空的?

SQL 查询 - 当我们在 where 子句中使用主键时更新/删除语句的性能

postgresql - 了解全文搜索查询中子句顺序的影响

php - 是什么导致我的 Laravel 8 应用程序出现此查询生成器错误?

javascript - 根据 HTML 规范对模块脚本执行严格的 MIME 类型检查