【问题标题】:multiple inheritance python Issue多重继承python问题
【发布时间】:2021-05-08 07:56:19
【问题描述】:

所以我目前正在为我的一个类学习 python 的继承,并且任务让我们对 ScientificSwimmer 类使用多重继承。当您尝试运行代码而不创建所述类的对象时,程序运行。但是,在创建该类的对象时,出现以下错误。任何建议或解决方案将不胜感激。 (在帖子中添加行号)

#creation of Human class
class Human:  

    def __init__(self, name, age): #talks a name and balance and creates a instance of class
        self.age = age
        self.name = name
    
    def hobby(self):#Hobby method
        print("Likes to watch Netflix")
        
    def info(self):#info method
        print(self.name, " is ", self.age, " years old.")
        

#creation of the Scientist class
class Scienctist(Human):
    
    def __init__(self, name, age, lab):
        super().__init__(name, age)
        self.lab = lab
        
    def hobby(self):
        print("Likes watching Bill Nye the science guy.")
        
    def labName(self):
        print("Works at the ", self.lab , "laboratory.")
        
#Creation of Swimmer Class
class Swimmer(Human):
    
    def __init__(self, name, age, hours):
(line 33)super().__init__(name, age)
        self.hours = hours
        
    def hobby(self):
        print("Likes to go swimming in the lake.")
        
    def SwimmingHours(self):
        print("Swims ", self.hours, "hours per week.")
        
#Creation of the ScientificSwimmer
class ScientificSwimmer(Scienctist, Swimmer):
    def __init__(self, name, age, lab, hours):
(line 58)Scienctist.__init__(self, name, age, lab)
        Swimmer.__init__(self, name, age, hours)

(line 66) person5 = ScientificSwimmer("John Smith", "30", "nuclear", "100")

错误:

File "E:\Python\CS112\lab7\People.py", line 66, in <module>
    person5 = ScientificSwimmer("John Smith", "30", "nuclear", "100")

  File "E:\Python\CS112\lab7\People.py", line 58, in __init__
    Scienctist.__init__(self, name, age, lab)

  File "E:\Python\CS112\lab7\People.py", line 33, in __init__
    super().__init__(name, age)

TypeError: __init__() missing 1 required positional argument: 'hours'

【问题讨论】:

  • 您必须使用super() 一致地调用继承的方法,或者根本不调用。在这种情况下,您不能始终如一地使用它,这涉及到与方法的继承版本不同的多重继承和参数列表。可能还有其他解决方案,但我建议将所有 super()s 替换为父类的显式名称,就像您在 ScientificSwimmer.__init__() 中所做的那样。

标签: python class multiple-inheritance


【解决方案1】:

您必须使用super() 来一致地调用继承的方法,或者根本不使用。在这种情况下,您不能始终如一地使用它,涉及多重继承和与方法的继承版本不同的参数列表。可能还有其他解决方案,但我建议将所有super()s 替换为父类的显式名称,就像您在ScientificSwimmer.__init__() 中所做的那样。

--commentjasonharper

【讨论】:

    【解决方案2】:
    # creation of Human class
    class Human:
    
        def __init__(self, name, age):  # talks a name and balance and creates a instance of class
            if hasattr(self, 'age'):
                return
    
            if hasattr(self, 'name'):
                return
            self.age = age
            self.name = name
    
        def hobby(self):  # Hobby method
            print("Likes to watch Netflix")
    
        def info(self):  # info method
            print(self.name, " is ", self.age, " years old.")
    
    
    # creation of the Scientist class
    class Scienctist(Human):
    
        def __init__(self, lab, **kw):
            super().__init__(**kw)
            self.lab = lab
    
        def hobby(self):
            print("Likes watching Bill Nye the science guy.")
    
        def labName(self):
            print("Works at the ", self.lab, "laboratory.")
    
    
    # Creation of Swimmer Class
    class Swimmer(Human):
    
        def __init__(self, hours, **kw):
            super().__init__(**kw)
            self.hours = hours
    
        def hobby(self):
            print("Likes to go swimming in the lake.")
    
        def SwimmingHours(self):
            print("Swims ", self.hours, "hours per week.")
    
    
    # Creation of the ScientificSwimmer
    class ScientificSwimmer(Scienctist, Swimmer):
        def __init__(self, name, age, lab, hours):
            super(ScientificSwimmer, self).__init__(name=name, age=age, lab=lab, hours=hours)
    
    
    if __name__ == '__main__':
        person5 = ScientificSwimmer(name="John Smith", age="30", lab="nuclear", hours="100")
    
    

    【讨论】:

      【解决方案3】:

      我会更改类,为每个类添加一个 **kwargs 参数。这是处理不同参数的最简单方法。

      #creation of Human class
      class Human:
      
          def __init__(self, name, age, **kwargs): #talks a name and balance and creates a instance of class
              self.age = age
              self.name = name
      
          def hobby(self):#Hobby method
              print("Likes to watch Netflix")
      
          def info(self):#info method
              print(self.name, " is ", self.age, " years old.")
      
      
      #creation of the Scientist class
      class Scienctist(Human):
      
          def __init__(self, name, age, lab, **kwargs):
              super().__init__(name, age, **kwargs)
              self.lab = lab
      
          def hobby(self):
              print("Likes watching Bill Nye the science guy.")
      
          def labName(self):
              print("Works at the ", self.lab , "laboratory.")
      
      #Creation of Swimmer Class
      class Swimmer(Human):
      
          def __init__(self, name, age, hours, **kwargs):
              super().__init__(name, age, **kwargs)
              self.hours = hours
      
          def hobby(self):
              print("Likes to go swimming in the lake.")
      
          def SwimmingHours(self):
              print("Swims ", self.hours, "hours per week.")
      
      #Creation of the ScientificSwimmer
      class ScientificSwimmer(Scienctist, Swimmer):
          def __init__(self, name, age, lab, hours, **kwargs):
              super().__init__(name=name, age=age, lab=lab, hours=hours, **kwargs)
      
      
      

      输出

      >>> person5 = ScientificSwimmer("John Smith", "30", "nuclear", "100")
      >>> person5
      <__main__.ScientificSwimmer at 0x248ca7fb730>
      
      >>> vars(person5)
      {'age': '30', 'name': 'John Smith', 'hours': '100', 'lab': 'nuclear'}
      
      
      

      【讨论】:

        【解决方案4】:

        对于像这样的父类共享一些实例属性的混乱多重继承模式,最好在每个类中显式声明父类:

        class Human:
            def __init__(self, name, age):  # talks a name and balance and creates a instance of class
                self.age = age
                self.name = name
        
            def hobby(self):  # Hobby method
                print("Likes to watch Netflix")
        
            def info(self):  # info method
                print(self.name, " is ", self.age, " years old.")
        
        class Scienctist(Human):
            def __init__(self, name, age, lab):
                Human.__init__(self, name, age)
                self.lab = lab
        
            def hobby(self):
                print("Likes watching Bill Nye the science guy.")
        
            def labName(self):
                print("Works at the ", self.lab, "laboratory.")
        
        class Swimmer(Human):
            def __init__(self, name, age, hours):
                Human.__init__(self,name, age)
                self.hours = hours
        
            def hobby(self):
                print("Likes to go swimming in the lake.")
        
            def swimmingHours(self):
                print("Swims ", self.hours, "hours per week.")
        
        class ScientificSwimmer(Scienctist, Swimmer):
            def __init__(self, name, age, lab, hours):
                Scienctist.__init__(self, name, age, lab)
                Swimmer.__init__(self, name, age, hours)
        
        person = ScientificSwimmer("John Smith", 30, "nuclear", 100)
        person.labName()
        person.swimmingHours()
        
        #Works at the  nuclear laboratory.
        #Swims  100 hours per week.
        

        【讨论】:

        • 好点,指出这种方法很混乱。 @Owen Boorn,我知道这是一项任务,所以您在这里可能别无选择;在现实世界中,由于这些复杂性和维护开销,您最好使用组合而不是继承。
        猜你喜欢
        • 2012-08-08
        • 2020-07-05
        • 2021-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-09
        相关资源
        最近更新 更多