0

The following code doesn't work the way I intended it to:

class A:
  def __init__(self, depth=0, places=list()):
    print(len(places))
    if depth < 3:
      places.append(2)
      a = A(depth + 1)

a = A()

How I'd expect this to work is that it creates three instances of class A each with a list called places with one element, 2. Instead, I get three elements, with the list [2], [2, 2], [2, 2, 2], respectively.

I'm assuming that creating an object of a class within that class this way causes the variables to act statically but I'm not sure why and how to write this code the way I'd like it to work.

quamrana
  • 37,849
  • 12
  • 53
  • 71
jbal
  • 15
  • 2

1 Answers1

2

The problem here is the places=list() default parameter. Its nothing to do with the class, but the way python parses the line. Effectively that line is executed once on the file parse, so that the value of list() is only computed once: on load.

This way when you make lots of a's, the second and third one is done.

What you should try is something like this (its true for function defs too):

class A:
    def __init__(self, depth=0, places=None):
       if not places:
           places = list()
       # ... continue with code

See http://docs.python-guide.org/en/latest/writing/gotchas/

quamrana
  • 37,849
  • 12
  • 53
  • 71
Jmons
  • 1,766
  • 17
  • 28