python - 子类 init 方法只调用基础初始化方法

标签 python python-3.x inheritance

我有一个派生类,它的 __init__ 方法只调用 super().__init(...)。但是,父类(super class)的参数列表很长,这使得列表很长,大部分都是样板文件:

def __init__(self, dataset, updater=None,
                 start_date=None,
                 end_date=None,
                 fill_missing_only=False,
                 total_sync: bool = False,
                 force: bool = False,
                 allow_missing: bool = False,
                 backfill=''):
        super().__init__(self, dataset, updater,start_date, end_date,fill_missing_only,total_sync,force,allow_missing,backfill)

有没有办法去掉它并让子类自动调用基类的 init() 方法?

最佳答案

我看到两种可能性:

  • 只要省略子类中的 __init__ 方法 - 如果您实际上没有覆盖任何东西。

  • 使用

    def __init__(*args, **kwargs):
        super().__init__(*args, **kwargs)
    

    如果您除了 super().__init__ 调用之外还做了一些其他事情,但不需要所有参数。

关于python - 子类 init 方法只调用基础初始化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41351181/

相关文章:

python - 在Python中将Dataframe写入和读取文件的正确方法

c++ - C++ 中类似 python 的字符串索引

django - Python:如何执行生成的代码?

python - 自定义 Python Wheel 文件的 Yocto Warrior 自定义 Bitbake 配方无法安装,因为找不到 pip3

c++ - 继承:没有合适的默认构造函数可用

python - 使用 CP1252 编码的文件的正则表达式

python-3.x - 从用户定义的模块导入方法会产生属性错误

python - 如何从 pandas 数据框中的多列中删除字符?

c++ - 我可以更改默认继承的访问器吗?

c# - 这种继承特性的用例是什么?