python - 多继承python问题

标签 python class multiple-inheritance

所以我目前正在为我的一个类学习 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'

最佳答案

You have to use super() for invoking inherited methods either consistently, or not at all. And you can't use it consistently in cases like this, that involve multiple inheritance and parameter lists that aren't the same as the inherited version of the method. There are probably other solutions, but I'd suggest replacing all super()s with the explicit name of the parent class, as you did in ScientificSwimmer.__init__().


-- comment来自 jasonharper

关于python - 多继承python问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66038465/

相关文章:

python - 如何将 url 参数作为字符串元组传递给 mysql 查询

python - 使用python从非常大的文本文件(16gb)中跳过一行的省时方法

c++ - 构造函数内部 "this"的 dynamic_cast

c++ - c++访问模板变量的方法

php - 使用方法访问类并实例化它们

Python 3.6.5 "Multiple bases have instance lay-out conflict"具有 __slots__ 的类的多重继承

c++ - 多重继承 : using a member function of a private base

python - 无法使用 python 3.2 运行调用子进程方法

python - django CMS 历史选项卡在哪里?

python - Kivy 从 kv 按钮运行功能