python中的链调用父初始化程序 [英] Chain-calling parent initialisers in python
问题描述
考虑一下-基类A,从A继承的类B,从B继承的类C.在初始化器中调用父类初始化器的通用方法是什么?如果这听起来仍然不太明确,请使用以下代码.
Consider this - a base class A, class B inheriting from A, class C inheriting from B. What is a generic way to call a parent class initialiser in an initialiser? If this still sounds too vague, here's some code.
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()
这就是我现在的做法.但这似乎还是太普通了-您仍然必须手动传递正确的类型.
This is how I do it now. But it still seems a bit too non-generic - you still must pass a correct type by hand.
现在,我尝试使用self.__class__
作为super()的第一个参数,但是,显然,它不起作用-如果将其放在C的初始化程序中-足够公平,B的初始化程序将被调用.如果在B中执行相同的操作,则"self"仍指向C的一个实例,因此您最终再次调用B的初始化程序(此操作以无限递归结束).
Now, I've tried using self.__class__
as a first argument to super(), but, obviously it doesn't work - if you put it in the initialiser for C - fair enough, B's initialiser gets called. If you do the same in B, "self" still points to an instance of C so you end up calling B's initialiser again (this ends in an infinite recursion).
目前无需考虑钻石继承,我只是想解决这个特定问题.
There is no need to think about diamond inheritance for now, I am just interested in solving this specific problem.
推荐答案
推荐的方法确实是推荐的方法(对于Python 2.x).
The way you are doing it is indeed the recommended one (for Python 2.x).
是否将类显式传递给super
的问题是样式问题,而不是功能问题.将类传递给super
符合Python的显式优于隐式"的哲学.
The issue of whether the class is passed explicitly to super
is a matter of style rather than functionality. Passing the class to super
fits in with Python's philosophy of "explicit is better than implicit".
这篇关于python中的链调用父初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!