python多重继承使用super将参数传递给构造函数 [英] python multiple inheritance passing arguments to constructors using super

查看:504
本文介绍了python多重继承使用super将参数传递给构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下python代码段

Consider the following snippet of python code

class A(object):
    def __init__(self, a):
        self.a = a

class B(A):
    def __init__(self, a, b):
        super(B, self).__init__(a)
        self.b = b

class C(A):
    def __init__(self, a, c):
        super(C, self).__init__(a)
        self.c = c

class D(B, C):
    def __init__(self, a, b, c, d):
        #super(D,self).__init__(a, b, c) ???
        self.d = d

我想知道如何将abc传递给相应的基类的构造函数.

I am wondering how can I pass a, b and c to corresponding base classes' constructors.

推荐答案

好吧,一般来说,在处理多重继承时,应该为多个继承设计您的基类.在您的示例中,类BC不是,因此您找不到在D中应用super的正确方法.

Well, when dealing with multiple inheritance in general, your base classes (unfortunately) should be designed for multiple inheritance. Classes B and C in your example aren't, and thus you couldn't find a proper way to apply super in D.

为多重继承设计基类的一种常见方法是让中级基类在其__init__方法中接受它们不打算使用的额外arg,并将其传递给它们. super通话.

One of the common ways of designing your base classes for multiple inheritance, is for the middle-level base classes to accept extra args in their __init__ method, which they are not intending to use, and pass them along to their super call.

这是在python中执行此操作的一种方法:

Here's one way to do it in python:

class A(object):
    def __init__(self,a):
        self.a=a

class B(A):
    def __init__(self,b,**kw):
        self.b=b
        super(B,self).__init__(**kw)

 class C(A):
    def __init__(self,c,**kw):
        self.c=c
        super(C,self).__init__(**kw)

class D(B,C):
    def __init__(self,a,b,c,d):
        super(D,self).__init__(a=a,b=b,c=c)
        self.d=d

这可以被视为令人失望,但这就是事实.

This can be viewed as disappointing, but that's just the way it is.

这篇关于python多重继承使用super将参数传递给构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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