为什么函数可以修改调用者感知的某些参数,而不能修改其他参数? [英] Why can a function modify some arguments as perceived by the caller, but not others?

查看:54
本文介绍了为什么函数可以修改调用者感知的某些参数,而不能修改其他参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解 Python 的变量作用域方法.在这个例子中,为什么 f() 能够改变 x 的值,正如在 main() 中所感知的那样,而不是n?

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 main(), but not the value of n?

def f(n, x):
    n = 2
    x.append(4)
    print('In f():', n, x)

def main():
    n = 1
    x = [0,1,2,3]
    print('Before:', n, x)
    f(n, x)
    print('After: ', n, x)

main()

输出:

Before: 1 [0, 1, 2, 3]
In f(): 2 [0, 1, 2, 3, 4]
After:  1 [0, 1, 2, 3, 4]

推荐答案

有些答案在函数调用的上下文中包含复制"一词.我觉得很混乱.

Some answers contain the word "copy" in a context of a function call. I find it confusing.

Python 不会复制对象在函数调用期间传递的永远.

Python doesn't copy objects you pass during a function call ever.

函数参数是名称.当您调用函数时,Python 会将这些参数绑定到您传递的任何对象(通过调用方作用域中的名称).

Function parameters are names. When you call a function Python binds these parameters to whatever objects you pass (via names in a caller scope).

对象可以是可变的(如列表)或不可变的(如整数、Python 中的字符串).您可以更改的可变对象.您不能更改名称,您只能将其绑定到另一个对象.

Objects can be mutable (like lists) or immutable (like integers, strings in Python). Mutable object you can change. You can't change a name, you just can bind it to another object.

你的例子不是关于范围或命名空间,它是关于命名和绑定Python 中对象的可变性.

Your example is not about scopes or namespaces, it is about naming and binding and mutability of an object in Python.

def f(n, x): # these `n`, `x` have nothing to do with `n` and `x` from main()
    n = 2    # put `n` label on `2` balloon
    x.append(4) # call `append` method of whatever object `x` is referring to.
    print('In f():', n, x)
    x = []   # put `x` label on `[]` ballon
    # x = [] has no effect on the original list that is passed into the function

这里有 其他语言中的变量与 Python 中的名称的区别.

这篇关于为什么函数可以修改调用者感知的某些参数,而不能修改其他参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆