python系统提供构造函数传入参数_python多继承使用super将参数传递给构造函数

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

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

解决方案

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.

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值