Extending classes __init__behavior for newbies

MRAB python at mrabarnett.plus.com
Sun Feb 13 23:21:56 CET 2011


On 13/02/2011 22:00, James Mills wrote:
> 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.
>
I would've done it this way:

class FasterShip(Ship):
     def __init__(self, speed=0, **kwargs):
         Ship.__init__(self, **kwargs)
         self.speed = speed



More information about the Python-list mailing list