classes and list as parameter, whats wrong?
James
spiralx at gmail.com
Fri Aug 26 05:42:04 EDT 2005
No, the default paramter LL is only ever created once, not
reinitialised every time the constructor is called - this is quite a
common gotcha! You want to do something like:
class cClass:
""" Base class to handle playlists, i.e. the files, the name, etc. """
def __init__(self, LL=None):
if LL == None:
LL = []
self.list=LL
def addFile(self,L):
self.list.append(L)
James
On 8/26/05, Dirk Zimmermann <python-list at d1z1.de> wrote:
> Hi!
>
> I have a problem in a program. And I don't understand what is going on.
> I can code something, that the "error" doesn't occur anymore. But I
> still don't know the reason and this is unsatisfactory: Did I understood
> something wrong or is there a bug? To make it short, I boiled down the
> program to the crucial part. It looks like this:
>
> ----------- START ------------
> #!/usr/bin/env python
>
> class cClass:
> """ Base class to handle playlists, i.e. the files, the name, etc. """
> def __init__(self, LL=[]):
> self.list=LL
> def addFile(self,L):
> self.list.append(L)
>
> def main():
> l1 = ['a','b','c']
> lNames=['n1','n2','n3']
> for name in lNames:
> objC=cClass()
> for each in l1:
> objC.addFile(each)
> print objC.list
> del objC
>
> if __name__ == "__main__":
> main()
> ----------- END ----------------
>
> If I start it, I get the following output:
>
> ['a', 'b', 'c']
> ['a', 'b', 'c', 'a', 'b', 'c']
> ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
>
>
> Why does this list grow? I thought, with every new instance the list LL
> is set to []?
>
> How can bring light in this?
>
>
> Best,
> Dirk
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list