【问题标题】:Inheritance not working in python code [closed]继承在python代码中不起作用[关闭]
【发布时间】:2016-12-09 17:02:52
【问题描述】:
class One(object):
    def __init__(self, i = 0):
        print('one', i)

class Two(One):
    def __init__(self, i = 0):
        super().__init__(i)
        print('two', i)

class First(object):
    def __init__(self, i = 0):
        print('first', i)

class Second(First):
    def __init__(self, i = 0):
        super().__init__(i)
        print('second', i)

class Third(Second, Two):
    def __init__(self, i = 0):
        super().__init__(i)
        print('third', i)

class Fourth(Two, Second):
    def __init__(self, i = 0):
        super().__init__(i)
        print('fourth', i)

输出:
第三(3):
前 3 个
第二个 3
第三个 3

第四(4):
一个 4
两个 4
第四 4

为什么继承不起作用,我该如何解决。
感谢您的帮助。

【问题讨论】:

  • 请描述您的实际问题。我向你保证继承是有效的。
  • 你的代码格式很糟糕,使用<br> 不是格式化它的方法。只需缩进四个空格。
  • 请修正您的代码格式!帖子编辑器中内置了一些工具来执行此操作。
  • 正如 Carcigenicate 所建议的那样 - 描述您所期望的行为,即“继承不起作用”是什么意思。它确实有效,问题是你期待一些不同的东西,但你没有描述什么。
  • 您的 quation 仍然缺少对您期望输出的正确描述。

标签: python python-3.x class multiple-inheritance


【解决方案1】:

您需要在基类OneFirst 中调用super().__init__() 以允许相邻类初始化。

class One(object):
    def __init__(self, i = 0):
        super().__init__()
        print('one', i)

....

class First(object):
    def __init__(self, i = 0):
        super().__init__()
        print('first', i)
....

>>> Fourth()
first 0
second 0
one 0
two 0
fourth 0

【讨论】:

  • Fourth(4)的输出不好,first和second仍然显示0,为什么?
  • 如果我在基类中传递参数,我会收到错误:TypeError: object.__init__() 没有参数
  • 在不知道您的实际用例的情况下,我绝对无法帮助您。我建议您尝试将当前类的名称作为 i 值传递,以查看 init 调用链,但我不确定您打算如何在实际代码中使用这样的设置。
  • 也许在pythontutor中逐步完成它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-28
  • 2021-02-26
  • 1970-01-01
  • 2016-12-05
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
相关资源
最近更新 更多