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

前端 未结 11 1234
盖世英雄少女心
盖世英雄少女心 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:47

    f doesn't actually alter the value of x (which is always the same reference to an instance of a list). Rather, it alters the contents of this list.

    In both cases, a copy of a reference is passed to the function. Inside the function,

    • n gets assigned a new value. Only the reference inside the function is modified, not the one outside it.
    • x does not get assigned a new value: neither the reference inside nor outside the function are modified. Instead, x’s value is modified.

    Since both the x inside the function and outside it refer to the same value, both see the modification. By contrast, the n inside the function and outside it refer to different values after n was reassigned inside the function.

提交回复
热议问题