optional argument to a subclass of a class

Peter Otten __peter__ at web.de
Fri May 21 14:48:27 EDT 2010


Alex Hall wrote:

> On 5/21/10, Christian Heimes <lists at cheimes.de> wrote:
>> Am 21.05.2010 04:56, schrieb Alex Hall:
>>> 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=[]):
>>
>> I hope you are aware that helpers.id() is called just once when the
>> *class* is defined and that the list weapons is shared across all
>> instances of the craft class. :)
> I know id is called once, but what do you mean weapons is shared?

All Craft instances for which you don't provide a weapons argument 
explicitly will share the same list. If you later append a weapon to that 
list all these Craft instances will see this change and get the extra 
weapon:

a = Craft("first")
b = Craft("second")
a.weapons.append("surprise")
print b.weapons # ['surprise']

Peter



More information about the Python-list mailing list