为什么不自动调用超类__init__方法? [英] Why aren't superclass __init__ methods automatically invoked?

查看:265
本文介绍了为什么不自动调用超类__init__方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Python设计者决定子类' __ init __()方法不会自动调用 __ init __()他们的超类方法,如在其他一些语言中? Pythonic和推荐的成语是否真的如下?

Why did the Python designers decide that subclasses' __init__() methods don't automatically call the __init__() methods of their superclasses, as in some other languages? Is the Pythonic and recommended idiom really like the following?

class Superclass(object):
    def __init__(self):
        print 'Do something'

class Subclass(Superclass):
    def __init__(self):
        super(Subclass, self).__init__()
        print 'Do something else'


推荐答案

关键区别在Python的 __ init __ 和其他语言构造函数之间是 __ init __ 不是一个构造函数:它是一个初始化程序(实际的构造函数(如果有的话,但是,见后面;-)是 __ new __ 和完全不同的工作方式)。虽然构建所有超类(并且毫无疑问,在继续向下构建之前这样做)显然是说你构建子类的实例,这显然是不是初始化的情况,因为有很多用例需要跳过,更改,控制超级类的初始化,如果有的话,在子类初始化的中间,

The crucial distinction between Python's __init__ and those other languages constructors is that __init__ is not a constructor: it's an initializer (the actual constructor (if any, but, see later;-) is __new__ and works completely differently again). While constructing all superclasses (and, no doubt, doing so "before" you continue constructing downwards) is obviously part of saying you're constructing a subclass's instance, that is clearly not the case for initializing, since there are many use cases in which superclasses' initialization needs to be skipped, altered, controlled -- happening, if at all, "in the middle" of the subclass initialization, and so forth.

基本上,初始化程序的超类委派在Python中不是自动的,原因完全相同,这种委托对于任何<而言也不是自动的/ strong>其他方法 - 并注意那些其他语言不会为任何其他方法执行自动超类委派... 只是用于构造函数(如果适用,析构函数) ,正如我所提到的那样, Python的 __ init __ 是什么。 ( __ new __ 的行为也很奇特,但与你的问题没有直接关系,因为 __ new __ 是如此奇特它实际上并不一定需要构造任何东西的构造函数 - 完全可以很好地返回现有实例,甚至是非实例......显然Python为你提供了一个很多更多的机制控制。你想到的其他语言,包括 __ new __ 本身没有自动委托! - 。

Basically, super-class delegation of the initializer is not automatic in Python for exactly the same reasons such delegation is also not automatic for any other methods -- and note that those "other languages" don't do automatic super-class delegation for any other method either... just for the constructor (and if applicable, destructor), which, as I mentioned, is not what Python's __init__ is. (Behavior of __new__ is also quite peculiar, though really not directly related to your question, since __new__ is such a peculiar constructor that it doesn't actually necessarily need to construct anything -- could perfectly well return an existing instance, or even a non-instance... clearly Python offers you a lot more control of the mechanics than the "other languages" you have in mind, which also includes having no automatic delegation in __new__ itself!-).

这篇关于为什么不自动调用超类__init__方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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