Why can a function modify some arguments as perceived by the caller, but not others?

前端 未结 11 1382
盖世英雄少女心
盖世英雄少女心 2020-11-21 07:10

I\'m trying to understand Python\'s approach to variable scope. In this example, why is f() able to alter the value of x, as perceived within

11条回答
  •  不要未来只要你来
    2020-11-21 07:40

    If the functions are re-written with completely different variables and we call id on them, it then illustrates the point well. I didn't get this at first and read jfs' post with the great explanation, so I tried to understand/convince myself:

    def f(y, z):
        y = 2
        z.append(4)
        print ('In f():             ', id(y), id(z))
    
    def main():
        n = 1
        x = [0,1,2,3]
        print ('Before in main:', n, x,id(n),id(x))
        f(n, x)
        print ('After in main:', n, x,id(n),id(x))
    
    main()
    Before in main: 1 [0, 1, 2, 3]   94635800628352 139808499830024
    In f():                          94635800628384 139808499830024
    After in main: 1 [0, 1, 2, 3, 4] 94635800628352 139808499830024
    

    z and x have the same id. Just different tags for the same underlying structure as the article says.

提交回复
热议问题