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

Bob Gailer bgailer at alum.rpi.edu
Sun Jun 25 22:45:21 CEST 2006


Barbara Schneider wrote:
> 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?
>   
When the function definition is processed, Python creates an empty list, 
which will be used as the default value for q whenever the function is 
called with no 2nd parameter. Any changes to that list are visible in 
any call to the function that has no 2nd parameter.

To get the behavior I think you want try:

    def __init__(self, q = None):
        if not q: q = []
        self.queue = q

-- 

Bob Gailer
510-978-4454



More information about the Tutor mailing list