相关疑难解决方法(0)

Python的super()如何与多重继承一起工作?

我是Python面向对象编程的新手,我很难理解super()函数(新样式类),尤其是涉及多重继承时.

例如,如果你有类似的东西:

class First(object):
    def __init__(self):
        print "first"

class Second(object):
    def __init__(self):
        print "second"

class Third(First, Second):
    def __init__(self):
        super(Third, self).__init__()
        print "that's it"
Run Code Online (Sandbox Code Playgroud)

我没有得到的是:Third()该类是否会继承构造函数方法?如果是,那么将使用super()运行哪一个?为什么?

如果你想运行另一个怎么办?我知道它与Python方法解析顺序(MRO)有关.

python multiple-inheritance

825
推荐指数
14
解决办法
30万
查看次数

多继承python问题

所以我目前正在为我的一个类学习 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 …
Run Code Online (Sandbox Code Playgroud)

python class multiple-inheritance

6
推荐指数
1
解决办法
162
查看次数

Python 多重继承 super().__init__()

我有两个类,它们的方法初始化了相同的参数__init__。我想继承“X”类中的两个类。但我会得到:TypeError: B.__init__() missing 1 required positional argument: 'my_param'

可重现的示例:

class A:
    def __init__(self, my_param):
        super().__init__()
        self.my_param = my_param


class B:
    def __init__(self, my_param):
        super().__init__()
        self.my_param = my_param * 2


class X(A, B):
    def __init__(self, my_param):
        super().__init__(my_param=my_param)

a = X(my_param=1)
print(a.my_param)
Run Code Online (Sandbox Code Playgroud)

A 和 B 是 Mixins,它们为子类提供附加功能。它们可以单独或一起使用。假设 A 类提供按 ID 搜索的 searchhc 功能,而 B 类提供按值搜索的功能。

有没有办法为 A 和 B 分别设置 my_param 或设置它而不会出现错误?

python inheritance multiple-inheritance

-2
推荐指数
1
解决办法
4947
查看次数

标签 统计

multiple-inheritance ×3

python ×3

class ×1

inheritance ×1