开发者

python classes and variable scope

开发者 https://www.devze.com 2023-03-05 07:55 出处:网络
class Test: def c(self, args): print args开发者_如何学JAVA def b(self, args): args.append(\'d\') def a(self):
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消