another question about classes and subclassing

Dave Angel davea at ieee.org
Tue May 18 21:31:11 EDT 2010


Alex Hall wrote:
> Hi again all,
> More about classes. I am still looking into my battleship game, and I
> will have several different craft. All craft have common attribs
> (position, alive, and so on) but each craft may be a surface ship,
> submarine, or airplane. All three are craft, but a submarine can be
> submerged or not, which does not apply to a surface ship or a plane,
> while a plane can be airborne or not, which is not applicable to the
> other two. Is there any advantage to creating a craft class:
>
> class craft():
>  #has attribs common to any and all craft
> #end class
>
> then doing something like:
>
> class submarine(craft):
>  #sub-specific attribs
> #end class
>
> How would I create a submarine, and then get at the craft-level
> attribs? Come to think of it, how would I pass anything to the craft
> constructor (position and alive, for example) when creating a new
> submarine object? Am I even doing this right to make submarine a
> subclass of craft? Thanks.
>
>   
Inside the __init__() method of Submarine, simply call the __init__() 
method of Craft, with appropriate parameters.

As for getting at the attributes of the Craft parent class, from a 
Submarine object, you simply reference the attributes as always.  If 
they're not overridden in Submarine, they'll be searched for in Craft.


DaveA




More information about the Python-list mailing list