python classes and variable scope
class Test:
def c(self, args):
print args开发者_如何学JAVA
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']?
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.
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.
精彩评论