shy*_*ent 279 python oop inheritance constructor
考虑一下 - 基类A,继承自A的类B,继承自B的类C.什么是在构造函数中调用父类构造函数的通用方法?如果这仍然听起来太模糊,这里有一些代码.
class A(object):
def __init__(self):
print "Initialiser A was called"
class B(A):
def __init__(self):
super(B,self).__init__()
print "Initialiser B was called"
class C(B):
def __init__(self):
super(C,self).__init__()
print "Initialiser C was called"
c = C()
Run Code Online (Sandbox Code Playgroud)
这就是我现在这样做的方式.但它仍然看起来有点过于非泛型 - 您仍然必须手动传递正确的类型.
现在,我尝试使用self.__class__作为super()的第一个参数,但是,显然它不起作用 - 如果你把它放在C的构造函数中 - 公平,B的构造函数被调用.如果你在B中做同样的事情,"self"仍然指向一个C的实例,所以你最终再次调用B的构造函数(这以无限递归结束).
现在没有必要考虑钻石继承,我只想解决这个具体问题.
iro*_*ggy 195
Python 3包含一个改进的super(),允许使用如下:
super().__init__(args)
Run Code Online (Sandbox Code Playgroud)
dF.*_*dF. 165
你的方式确实是推荐的(对于Python 2.x).
是否明确传递类super的问题是风格而不是功能问题.通过这个类来super适应Python的"明确比隐含更好"的哲学.
Jay*_*ikh 25
你可以简单地写:
class A(object):
def __init__(self):
print "Initialiser A was called"
class B(A):
def __init__(self):
A.__init__(self)
# A.__init__(self,<parameters>) if you want to call with parameters
print "Initialiser B was called"
class C(B):
def __init__(self):
# A.__init__(self) # if you want to call most super class...
B.__init__(self)
print "Initialiser C was called"
Run Code Online (Sandbox Code Playgroud)