链式调用父构造函数在python中 [英] Chain-calling parent constructors in python

查看:183
本文介绍了链式调用父构造函数在python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个 - 基类A,类B继承自A,类C继承自B.什么是在构造函数中调用父类构造函数的通用方法?如果这仍然听起来太含糊,这里有一些代码。

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 constructor in a constructor? If this still sounds too vague, here's some code.

class A(object):
    def __init__(self):
        print "Constructor A was called"

class B(A):
    def __init__(self):
        super(B,self).__init__()
        print "Constructor B was called"

class C(B):
    def __init__(self):
        super(C,self).__init__()
        print "Constructor 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 constructor for C - fair enough, B's constructor gets called. If you do the same in B, "self" still points to an instance of C so you end up calling B's constructor 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆