[Tutor] beginner: using optional agument in __init__ breaks my code

Barbara Schneider brb.shneider at yahoo.de
Sun Jun 25 17:21:35 CEST 2006

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):

    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

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.

Telefonate ohne weitere Kosten vom PC zum PC: http://messenger.yahoo.de

More information about the Tutor mailing list