Extending classes __init__behavior for newbies

James Mills prologic at shortcircuit.net.au
Sun Feb 13 23:00:19 CET 2011


On Mon, Feb 14, 2011 at 7:17 AM, Benjamin J. Racine
<bjracine at glosten.com> wrote:
> I don't quite understand the interplay of the two different __init__ methods
> when trying to extend a class.  Below is my hack attempt at doing so...
> class ship(object):
>     def __init__(self,l=0,b=0,t=0,name=''):
>        self.l = l
>         self.b = b
>         self.t = t
>         self.name = name
>     def make_it_deeper(self,t):
>         self.t = self.t - t
> class fast_ship(ship):
>     def __init__(self,speed = 0):
>         self.speed = speed
> my_ship = fast_ship(l = 100,b = 50, t = 10, name = 'cutter',speed = 10)
>
> If anyone would be so kind as to show me how to get the intended effect that
> I've hinted at, I would be most grateful,

When you subclass a base class (ship in your example) you need
to call it's parent (or super) methods. This includes the constructor
(__init__).

The standard way of doing this in Python is:

class FasterShip(Ship):

    def __init__(self, l=0,b=0,t=0,name='', speed=0):
        super(FasterShip, self).__init__(l, b, t, name)

        self.speed = speed

This ensures that the constructor of the base class (Ship) gets called
and the object initialized with the attributes you've defined.

Note for convention reasons I've also included proper class names
in the example. Classes normally start with an Upper case letter.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"



More information about the Python-list mailing list