What am I doing wrong?

Larry Bates larry.bates at websafe.com
Wed Sep 21 09:38:27 EDT 2005


You have been bitten by a well known "feature".  You used
a mutable as default value in your argument list for __init__.

See:
http://www.nexedi.org/sections/education/python/tips_and_tricks/python_and_mutable_n/view


It would be better to write:

class structure:
    def __init__(self, folders = None):
        self.folders=folders or []

-Larry Bates


keithlackey wrote:
> I'm relatively new to python and I've run into this problem.
> 
> 
> DECLARING CLASS
> 
> 	class structure:
>     		def __init__(self, folders = []):        
>        		self.folders = folders
>         
>     	def add_folder(self, folder):
>        	self.folders.append(tuple(folder))
> 
> 
> 
> Now I try to make an instance of this class
> 
> 	structure1 = structure()
> 	structure1.add_folder([('foo'),])
> 	print structure1.folders
> 
> This returns: [('foo',)]
> 
> This works fine. But when I try to make another instance of that class...
> 
> 	structure2 = structure()
> 	print structure2.folders
> 
> This now also returns: [('foo',)]
> Even though I haven't added any folders to this new instance
> 
> What am I doing wrong?
> 



More information about the Python-list mailing list