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

查看:31
本文介绍了为什么不自动调用超类 __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 中不是自动的,原因完全相同,这种委托对于任何其他方法也不是自动的——并注意那些其他语言"不也不要为任何其他方法执行自动超类委托...只是为构造函数(如果适用,析构函数),正如我所提到的,不是Python 的 __init__ 是什么.(__new__ 的行为也很奇特,虽然实际上与您的问题没有直接关系,因为 __new__ 是一个如此奇特的构造函数,它实际上并不一定需要构造任何东西-- 可以完美地返回现有实例,甚至是非实例......很明显,Python 为您提供了比您心目中的其他语言"更多很多 的机制控制,这 很多em>还包括在 __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天全站免登陆