fil*_*ble 5 python oop inheritance
您好,社区,我正在学习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()当我想调用两个继承类的构造函数时,我是否使用了错误?
如何才能正确地从多个基类继承并使用主类中的变量和方法而不会出现此错误?
谢谢.
您需要添加super对Base1 的调用,以便__init__在Base1之后可以调用Base2 。您还可以添加super对Base2 的调用。没必要,但是不会受伤。
class Base1(object):
def __init__(self):
super(Base1, self).__init__()
self.base1var = "this is base1"
class Base2(object):
def __init__(self):
#super(Base2, self).__init__()
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)
输出
this is base1
this is base2
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您确实应该使用Python3。super在现代Python中要好得多。:)