What am I doing wrong?

K

keithlackey

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?
 
S

Scott David Daniels

keithlackey said:
I'm relatively new to python and I've run into this problem.
This has two very standard mistakes:
First, as noted by Sybren, messages should just use spaces in order to
be readable.

After correcting that one:
class structure:
def __init__(self, folders = []):
self.folders = folders
> ...

Here is the second one. Default args are not rebuilt, but shared.
The correct way to do this is:
class structure:
def __init__(self, folders=None):
if folders is None:
self.folders = []
else:
self.folders = folders
...

--Scott David Daniels
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,264
Messages
2,571,323
Members
48,005
Latest member
ChasityFan

Latest Threads

Top