optional argument to a subclass of a class

Patrick Maupin pmaupin at gmail.com
Thu May 20 23:04:53 EDT 2010


On May 20, 9:56 pm, Alex Hall <mehg... at gmail.com> wrote:
> Hi all,
> I am now trying to allow my classes, all of which subclass a single
> class (if that is the term), to provide optional arguments. Here is
> some of my code:
>
> class Craft():
>  def __init__(self,
>  name,
>  isAircraft=False,
>  id=helpers.id(),
>  hits=0,
>  weapons=[]):
>   self.name=name
>   self.id=id
>   self.hits=hits
>   self.weapons=weapons
>   self.isAircraft=isAircraft
>  #end def
> #end class
>
> #now a class for each type of craft in the game
> #each will subclass the Craft class, but each also has its own settings
>
> class Battleship(Craft):
>  def __init__(self,
>  name,
>  maxHits):
>   Craft.__init__(self, name)
>   self.maxHits=maxHits
>   self.length=maxHits #in Battleship, each ship's length is the same
> as how many times it can be hit
>  #end def
> #end class
>
> I want to be able to say something like
> b=Battleship("battleship1", 4, weapons=["missile1","missile2"])
> When I do that, though, I get a traceback on the above line saying
> "type error: __init__() got an unexpected keyword argument 'weapons'".
> What did I do wrong / what do I need to change so that any Craft
> (Battleship, Carrier, and so on) can optionally provide a list of
> weapons, or any other arguments to which I assign default values in my
> Craft class? I hope this makes sense.
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehg... at gmail.com;http://www.facebook.com/mehgcap

You overrode the __init__method from the superclass.

One thing you can do is in battleship, you can accept additional
keyword arguments:

    def __init__(self, name, ..., **kw):

Then you could invoke the superclass's init:

    Craft.__init__(self, name, **kw)

Regards,
Pat



More information about the Python-list mailing list