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__()
3
  • 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
    May 16, 2011 at 7:22
  • @Keith: correct, although using old-style classes these days is not recommended, since it's a very old feature May 16, 2011 at 7:30
  • 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.
    – Keith
    May 16, 2011 at 8:44
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.