optional argument to a subclass of a class

Ethan Furman ethan at stoneleaf.us
Fri May 21 15:20:59 EDT 2010


Alex Hall wrote:
> On 5/20/10, alex23 <wuwei23 at gmail.com> wrote:
> I have since updated each ship's
> __init__ to accept all the arguments that Craft accepts so that I can
> support all optional arguments, 

Ick.  Now you'll have to change several things if you make one change to 
the Craft class.  Better to do it this way:

[borrowing Peter's example]

class Craft(object):
     def __init__(self, name, id=None, weapons=None):
         if id is None:
             id = helpers.id()
         if weapons is None:
             weapons = []
         self.name = name
         self.id = id
         self.weapons = weapons

class Battleship(Craft):
     def __init__(self, name, max_hits=None, **kwds):
         Craft.__init__(self, name, **kwds)
         self.max_hits = max_hits



Notice the **kwds in Battleships's init, both in the parameter line, and 
in the call to Craft's init.  This way all keyword arguments that 
Battleship doesn't directly support will be passed through to Craft.

~Ethan~



More information about the Python-list mailing list