Python __init__语法 [英] Python __init__ syntax

查看:127
本文介绍了Python __init__语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习Python时我对使用继承的类初始化的语法有些混乱。在各种示例中,我看到类似下面的内容:

While learning Python I'm having some confusion over the syntax of the initialization of classes using inheritance. In various examples I've seen something like the following:

class Foo(Bar):
    def __init__(self, arg, parent = None):
        Bar.__init__(self, parent)
        self.Baz = arg
        etc.

虽然有时只是

class Foo(Bar):
    def __init__(self, arg):
        Bar.__init__(self)
        etc.

什么时候要确保使用parent作为初始化函数的参数?感谢。

When would one want to make sure to use "parent" as an argument to the initialization functions? Thanks.

推荐答案

一般来说,传递 parent 当父类的构造函数显式地需要这样的参数时。这在一些层次结构中使用,例如PyQt。

Generally passing parent is not something that's required, only when the parent class's constructor explicitly needs such an argument. This is used in some hierarchies, such as PyQt.

父类初始化的好习惯是使用 super

And a good idiom of parent class initialization is to use super:

class Child(Father):
  def __init__(self):
    super(Child, self).__init__()

这篇关于Python __init__语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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