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

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

    You've got a number of answers already, and I broadly agree with J.F. Sebastian, but you might find this useful as a shortcut:

    Any time you see varname =, you're creating a new name binding within the function's scope. Whatever value varname was bound to before is lost within this scope.

    Any time you see varname.foo() you're calling a method on varname. The method may alter varname (e.g. list.append). varname (or, rather, the object that varname names) may exist in more than one scope, and since it's the same object, any changes will be visible in all scopes.

    [note that the global keyword creates an exception to the first case]

提交回复
热议问题