optional argument to a subclass of a class
Alex Hall
mehgcap at gmail.com
Fri May 21 16:09:56 EDT 2010
On 5/21/10, Ethan Furman <ethan at stoneleaf.us> wrote:
> 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):
Curious: I do not pass Craft this "object" keyword and I have no
problems. What is it for? Just a convention, something like self being
called self?
> 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.
Thanks, the **kwords makes sense!! I implemented it much as you
described, and life is much easier; each ship or aircraft now has a
simple constructor, and I am still free to change any attrib I want
later or at creation time. A very powerful concept, and I now have
2-line constructors.
class Battleship(Craft):
def __init__(self, name, **kwords):
Craft.__init__(self, name, maxHits=4, **kwords) #call the
superclass's __init__
class Carrier(Craft):
def __init__(self, name, **kwords):
Craft.__init__(self, name, maxHits=5, **kwords) #call the
superclass's __init__
>
> ~Ethan~
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap
More information about the Python-list
mailing list