[Tutor] beginner: using optional agument in __init__ breaks my code
Karl Pflästerer
khp at pflaesterer.de
Sun Jun 25 21:01:58 CEST 2006
On 25 Jun 2006, brb.shneider at yahoo.de wrote:
[...]
> This code works as intended. Now my idea is to provide
> an optional argument to the constructor. So I change
> it to:
>
> def __init__(self, q =[]):
> self.queue = q
>
> Now, something very strange happens:
>
>>>> a = Queue()
>>>> b = Queue()
>>>> a.insert(12)
>>>> print b
> [12]
>>>>
>
> Why do a and b share the same data? "self.queue" is
> supposed to be an instance variable. What does may
> change of the __init__ method do here?
The values of optional arguments are only once evaluated (when Python
reads the definition). If you place there mutable objects like e.g. a
list most of the time the effect you see is not what you want. So you
have to write it a bit different.
def __init__(self, q = None):
if not q: q = []
self.queue = q
or
def __init__(self, q = None):
self.queue = q or []
Now you get a fresh list for each instance.
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list