Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python __init__ syntax

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.

While sometimes it's just

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

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

like image 825
Bitrex Avatar asked May 16 '11 06:05

Bitrex


1 Answers

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.

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

class Child(Father):
  def __init__(self):
    super(Child, self).__init__()
like image 177
Eli Bendersky Avatar answered Sep 28 '22 04:09

Eli Bendersky