11

I'm confused about some examples I've seen of initializing classes using inheritance. Some of them look like:

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

While others are simpler:

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

What is the purpose of using a "parent" argument to __init__?

2 Answers 2

9

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__()
Sign up to request clarification or add additional context in comments.

3 Comments

But super() only works with new-style classes in Python 2, or Python 3. It doesn't work with old-style classes in Python 2. Make sure your base class is a new-style class (inherits from object).
@Keith: correct, although using old-style classes these days is not recommended, since it's a very old feature
Exactly, but some people still do it and the OP seemed to be following an old example. So I thought I'd point that out, just in case.
3

In your example the variable "parent" is misleading. Simply the parent class COULD require additional arguments that must be provided

class Pet:
    def __init__(self,name):
        self.name = name

class Dog(Pet):
    def __init__(self,name,age):
        Pet.__init__(self,name)
        self.age = age

In this example the parent class Pet requires an attribute (name), and the child class provides it

As pointed out, use "super" syntax to call parent classes methods

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.