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

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

问题描述

我有一个基类有很多 __ init __ 参数:

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

def 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 __ code> __ init __ 的每个继承类中的code>方法,但这将是一个严重的代码重复:

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:

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

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

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

...


$ b b

自动调用超类 __ init __ 最灵活的方法是什么?

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天全站免登陆