What am I doing wrong?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • keithlackey

    #1

    What am I doing wrong?

    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.ap pend(tuple(fold er))



    Now I try to make an instance of this class

    structure1 = structure()
    structure1.add_ folder([('foo'),])
    print structure1.fold ers

    This returns: [('foo',)]

    This works fine. But when I try to make another instance of that class...

    structure2 = structure()
    print structure2.fold ers

    This now also returns: [('foo',)]
    Even though I haven't added any folders to this new instance

    What am I doing wrong?

  • Larry Bates

    #2
    Re: What am I doing wrong?

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

    See:



    It would be better to write:

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

    -Larry Bates


    keithlackey wrote:[color=blue]
    > 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.ap pend(tuple(fold er))
    >
    >
    >
    > Now I try to make an instance of this class
    >
    > structure1 = structure()
    > structure1.add_ folder([('foo'),])
    > print structure1.fold ers
    >
    > This returns: [('foo',)]
    >
    > This works fine. But when I try to make another instance of that class...
    >
    > structure2 = structure()
    > print structure2.fold ers
    >
    > This now also returns: [('foo',)]
    > Even though I haven't added any folders to this new instance
    >
    > What am I doing wrong?
    >[/color]

    Comment

    • Scott David Daniels

      #3
      Re: What am I doing wrong?

      keithlackey wrote:[color=blue]
      > I'm relatively new to python and I've run into this problem.[/color]
      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:[color=blue]
      > class structure:
      > def __init__(self, folders = []):
      > self.folders = folders
      > ...[/color]

      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
      Scott.Daniels@A cm.Org

      Comment

      Working...