[Tutor] beginner: using optional agument in __init__ breaks my code
Hello Group, I am puzzled about this: The following code implements a simple FIFO object. class Queue: "Implementing a FIFO data structure." # Methods def __init__(self): self.queue = [] def emptyP(self): return (self.queue == []) def insert(self, item): self.queue.append(item) def remove(self): if not self.emptyP(): return self.queue.pop(0) def __str__(self): return str(self.queue) 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? Thanx for your help. Barb ___ Telefonate ohne weitere Kosten vom PC zum PC: http://messenger.yahoo.de ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] beginner: using optional agument in __init__ breaks my code
--- Karl Pflästerer <[EMAIL PROTECTED]> schrieb: > > 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 Thank you very much. I will use your code as a "recipe", while I still try to understand the mechanism and the reasons behind it. For me this feels odd. Barb ___ Gesendet von Yahoo! Mail - Jetzt mit 1GB Speicher kostenlos - Hier anmelden: http://mail.yahoo.de ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor