| 查看: 702 | 回复: 3 | ||
tuburfransth金虫 (正式写手)
|
[求助]
Python多重继承怎么初始化?
|
|
代码如下: class A(object): def __init__(self, a): print('__init__ A', str(a)) self.A = a class B(A): def __init__(self, a, b): super(B, self).__init__(a) print('__init__ B', str(b)) self.B = b class C(A): def __init__(self, a, c): super(C, self).__init__(a) print('__init__ C', str(c)) self.C = c class D(B, C): def __init__(self, a, b, c, d): B.__init__(self, a, b) # 这行及下行代码有问题,貌似对基类A进行了两次初始化 C.__init__(self, a, c) print('__init__ D', str(d)) self.D = d shanghe = D('x', 'y', 'z', 'k') ------------------------------------------------------------------------------------------------------------------- Traceback (most recent call last): File "test.py", line 25, in <module> shanghe = D('x', 'y', 'z', 'k') File "test.py", line 20, in __init__ B.__init__(self, a, b) File "test.py", line 8, in __init__ super(B, self).__init__(a) TypeError: __init__() missing 1 required positional argument: 'c' ----------------------------------------------------------------------------------------------------------- 说明:A是基类,B和C都继承A,而D同时继承B和C,问题出在注释那一行及下一行,这两行初始化代码应该怎么写? 还有一个问题就是:B和C都继承了A,那么假如A中有一个函数名为getname(),class D(B, C):会导致getname()函数被覆盖一次吗?也就是说由于B和C都继承了A中的getname()函数,导致有一个被覆盖了,是不是这样? |
» 猜你喜欢
基金申报
已经有3人回复
国自然申请面上模板最新2026版出了吗?
已经有9人回复
溴的反应液脱色
已经有6人回复
纳米粒子粒径的测量
已经有7人回复
常年博士招收(双一流,工科)
已经有4人回复
推荐一本书
已经有10人回复
参与限项
已经有5人回复
有没有人能给点建议
已经有5人回复
假如你的研究生提出不合理要求
已经有12人回复
萌生出自己或许不适合搞科研的想法,现在跑or等等看?
已经有4人回复
tuburfransth
金虫 (正式写手)
- 应助: 9 (幼儿园)
- 金币: 2380.1
- 散金: 68
- 红花: 5
- 帖子: 384
- 在线: 124.8小时
- 虫号: 3425987
- 注册: 2014-09-18
- 性别: GG
- 专业: 模式识别
|
自己尝试修改了几处,运行结果和预想的一样,修改后的代码如下: class A(object): def __init__(self, a): print('__init__ A', str(a)) self.A = a class B(A): def __init__(self, a, b): B.__init__(self, a) # 修改此处,不知道为什么super(B, self).__init__(a)会有问题 print('__init__ B', str(b)) self.B = b class C(A): def __init__(self, a, c): C.__init__(self, a) # 修改此处, 不知道为什么super(C, self).__init__(a)会有问题 print('__init__ C', str(c)) self.C = c class D(B, C): def __init__(self, a, b, c, d): B.__init__(self, a, b) # 这行及下行代码有问题,貌似对基类A进行了两次初始化 C.__init__(self, a, c) print('__init__ D', str(d)) self.D = d shanghe = D('x', 'y', 'z', 'k') |
2楼2016-12-13 18:27:59
ygidtu
新虫 (正式写手)
- 应助: 4 (幼儿园)
- 金币: 1690.7
- 散金: 798
- 红花: 3
- 帖子: 419
- 在线: 117.7小时
- 虫号: 2854989
- 注册: 2013-12-07
- 性别: GG
- 专业: 生物信息学
|
两次A的初始化很正常吧,你B是继承A的,C也是继承A的,然后D里同时有BC,不就是包含了两个A?所以A有的那个函数肯定被BC玩坏了,多重继承我从来没考虑过同时继承同一个父类衍生出来的两个子类,所以还真不知道怎么解决 发自小木虫Android客户端 |
3楼2016-12-14 09:31:20
baichi121234
禁虫 (职业作家)
|
本帖内容被屏蔽 |
4楼2016-12-14 09:36:14












回复此楼