多重继承的时候需要用super函数的问题
请问如果在多重继承的时候需要用super函数来继承的两个属性或者类方法分别来自于两个父类,应该要怎么写super函数?比如grade和interest分别来自于A和B
class C(A, B): def __init__(self, grade, interest): super(C, self).__init__(grade, interest)
这样写会不会出问题,万一A和B中都有grade 和interest属性呢?
请问如果在多重继承的时候需要用super函数来继承的两个属性或者类方法分别来自于两个父类,应该要怎么写super函数?比如grade和interest分别来自于A和B
class C(A, B): def __init__(self, grade, interest): super(C, self).__init__(grade, interest)
这样写会不会出问题,万一A和B中都有grade 和interest属性呢?
2015-05-13
In [14]: class A(object): ....: def __init__(self, grade, interest): ....: print "I am an instance of A" ....: self.grade = grade ....: self.interest = interest ....: In [15]: class B(object): ....: def __init__(self, grade, interest): ....: print "I am an instance of B" ....: self.grade = grade ....: self.interest = interest ....: In [16]: class C(A, B): ....: def __init__(self, grade, interest): ....: print "I am an instance of C" ....: super(C,self).__init__(grade, interest) ....: In [17]: c = C("1","football") I am an instance of C I am an instance of A
自己编个小例子就可以看到解答了,这样写的“后果”就是B的__init__没有被调用,我试了其他例子,好像python都只用最近的那个父类,比如A。
举报