0
class Test:

    def c(self, args):
        print args

    def b(self, args):
        args.append('d')

    def a(self):
        args = ['a', 'b', 'c']
        self.b(args)
        self.c(args)

Test().a()

Why doesn't this print ['a', 'b', 'c']?

makes
  • 6,438
  • 3
  • 40
  • 58
Russell
  • 2,692
  • 5
  • 23
  • 24
  • BTW, this has nothing to do with Python classes or variable scope. It's pass-by-value vs. pass-by-reference. Python uses the latter for objects. – Michael Lorton May 13 '11 at 01:56
  • I wish I could accept both as answers. I appreciate the link that mizo provided but I'm marking Wern as the answer for two reasons: a) He posted first b) He has only been a member for 11 days now. – Russell May 13 '11 at 12:43

2 Answers2

2

When you pass a list to a function, you're really passing it a pointer to the list and not a copy of the list. So b is appending a value to the original args, not its own local copy of it.

Wern
  • 481
  • 1
  • 3
  • 6
1

The parameter you pass to methods b and c is a reference to the list args, not a copy of it. In method b, you append to the same list you created in method a.

See this answer for a more detailed explanation on parameter passing in Python.

Community
  • 1
  • 1
makes
  • 6,438
  • 3
  • 40
  • 58