我正在努力了解它的用法super().从它的外观来看,可以创建两个子类,就好了.
我很想知道以下2个孩子班级之间的实际差异.
class Base(object):
def __init__(self):
print "Base created"
class ChildA(Base):
def __init__(self):
Base.__init__(self)
class ChildB(Base):
def __init__(self):
super(ChildB, self).__init__()
ChildA()
ChildB()
Run Code Online (Sandbox Code Playgroud) 您好,社区,我正在学习OOPS概念与python作为我的课程的一部分.我在python中遇到多重继承问题.以下是我的代码:
#!/usr/bin/env python
class Base1(object):
def __init__(self):
self.base1var = "this is base1"
class Base2(object):
def __init__(self):
self.base2var = "this is base2"
class MainClass(Base1, Base2):
def __init__(self):
super(MainClass, self).__init__()
if __name__ == "__main__":
a = MainClass()
print a.base1var
print a.base2var
Run Code Online (Sandbox Code Playgroud)
并且在运行时,我收到以下错误
print a.base2var
AttributeError: 'MainClass' object has no attribute 'base2var'
Run Code Online (Sandbox Code Playgroud)
如果我交换继承的类的顺序,则错误中的变量名会相应地更改.
super()当我想调用两个继承类的构造函数时,我是否使用了错误?
如何才能正确地从多个基类继承并使用主类中的变量和方法而不会出现此错误?
谢谢.