python中的链调用父初始化器 [英] Chain-calling parent initialisers in python

查看:19
本文介绍了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 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屋!

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