Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Having the language force the super class to initialize before or after means that you lose functionality. A subclass may depend on a superclass's initialization to be run first, or vice versa.</p> <p>In addition, it wouldn't have any way of knowing what arguments to pass -- subclasses decide what values are passed to an initializer, which gives more flexibility over automatically passing all arguments.</p> <p>An alternative method of initializing the super-class is by using <a href="http://docs.python.org/library/functions.html#super">super</a>, though this will actually initialize the super-class of <code>self</code> dynamically, by looking it up in the object's <code>__mro__</code> (method resolution order)</p> <p>In python 2:</p> <pre><code>super(self, Dog).__init__(self, name, "Dog") </code></pre> <p>In python 3, you can further reduce the syntax, and avoid repeating yourself:</p> <pre><code>super().__init__(self, name, "Dog") </code></pre> <p><strong>Edit</strong>:</p> <p>Since you're not actually using the <code>name</code> argument passed to dog, you can further reduce some syntax, by accepting arbitrary keyword and positional arguments in the <code>Dog</code> initializer, and passing them up the initialization chain:</p> <pre><code>class Dog(Pet): def __init__(self, chases_cats, *args, **kwargs): Pet.__init__(self, *args, species="Dog", **kwargs) self.chases_cats = chases_cats class Pet(object): def __init__(self, name, species, *args, **kwargs): self.name = name self.species = species </code></pre> <p>In your scenario, the initializer might be simple enough to not need this, but it's useful to know for when you have more arguments, and/or a deeper class hierarchy.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload