Python:继承超类 __init__ [英] Python: Inherit the superclass __init__

查看:39
本文介绍了Python:继承超类 __init__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有很多 __init__ 参数的基类:

I have a base class with a lot of __init__ arguments:

class BaseClass(object):
    def __init__(self, a, b, c, d, e, f, ...):
        self._a=a+b
        self._b=b if b else a
        ...

所有继承类都应该运行基类的__init__方法.

All the inheriting classes should run __init__ method of the base class.

我可以在每个继承类中编写一个 __init__() 方法来调用超类 __init__,但这将是一个严重的代码重复:

I can write a __init__() method in each of the inheriting classes that would call the superclass __init__, but that would be a serious code duplication:

class A(BaseClass):
    def __init__(self, a, b, c, d, e, f, ...):
        super(A, self).__init__(a, b, c, d, e, f, ...)

class B(BaseClass):
    def __init__(self, a, b, c, d, e, f, ...):
        super(A, self).__init__(a, b, c, d, e, f, ...)

class C(BaseClass):
    def __init__(self, a, b, c, d, e, f, ...):
        super(A, self).__init__(a, b, c, d, e, f, ...)

...

自动调用超类 __init__ 的最 Pythonic 的方法是什么?

What's the most Pythonic way to automatically call the superclass __init__?

推荐答案

super(SubClass, self).__init__(...)

考虑使用 *args 和 **kw 如果它有助于解决您的可变噩梦.

Consider using *args and **kw if it helps solving your variable nightmare.

这篇关于Python:继承超类 __init__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆