【问题标题】:Is there a way for the child function that will inherit more than one parent function to access all of the parent's methods?有没有办法让子函数继承多个父函数来访问所有父函数?
【发布时间】:2020-08-06 06:10:16
【问题描述】:

创建继承前两个类属性的第三个类时出现错误。第一个类的函数将通过,但是当访问第二个类的函数时,我得到一个错误:

class3' object has no attribute 'othernum

代码如下:

class class1():
    def __init__(self):
        self.number = 10000
    def getNum(self):
        return self.number
    
class class2():
    def __init__(self):
        self.othernum = 1111
    def displaynum(self):
        return self.othernum

class class3(class1, class2):
    pass

newperson = class3()
print(newperson.getNum())
print(newperson.displaynum())

【问题讨论】:

    标签: python-3.x class oop inheritance


    【解决方案1】:

    找到答案了。

    class class3(class1, class2):
        def __init__(self):
            class1.__init__(self)
            class2.__init__(self)
    

    【讨论】:

      【解决方案2】:

      @Ishaan Sathaye 提供的答案确实是正确的。但请注意,在多重继承层次结构中初始化基类有多种机制。请参阅Calling parent class init with multiple inheritance, what's the right way?,特别是标题为所有基类都是为协作继承而设计的部分。

      因此,如果您的 3 个类是为协作继承而设计的,我们将:

      class class1():
          def __init__(self):
              super().__init__()
              self.number = 10000
          def getNum(self):
              return self.number
      
      class class2():
          def __init__(self):
              super().__init__()
              self.othernum = 1111
          def displaynum(self):
              return self.othernum
      
      class class3(class1, class2):
          def __init__(self):
              super().__init__()
      
      newperson = class3()
      print(newperson.getNum())
      print(newperson.displaynum())
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-04
        • 1970-01-01
        • 1970-01-01
        • 2019-08-10
        • 1970-01-01
        • 2021-05-21
        • 2011-01-21
        • 2021-11-13
        相关资源
        最近更新 更多