python - 为什么函数可以修改调用者感知的某些参数,而不能修改其他参数?

我试图了解 Python 的变量范围方法。在这个例子中,为什么 f() 能够改变 x 的值,正如在 main() 中所感知的那样,但不能改变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]

最佳答案

有些答案在函数调用的上下文中包含“复制”一词。我觉得很困惑。

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

函数参数是名称。当您调用函数时,Python 会将这些参数绑定(bind)到您传递的任何对象(通过调用者范围内的名称)。

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

您的示例与 scopes or namespaces 无关, 大约是 naming and binding和 mutability of an object在 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

the difference between variables in other languages and names in Python 上的图片不错.

https://stackoverflow.com/questions/575196/

相关文章:

python - 安装pycurl时出现"Could not run curl-config: [E

linux - 如何链接到特定的 glibc 版本?

linux - 确保只有一个 Bash 脚本实例正在运行的最佳方法是什么?

shell - 如何将文本 append 到文件?

python - virtualenv和pyenv是什么关系?

python - 为什么我们不应该在 py 脚本中使用 sys.setdefaultencoding

linux - 如何使用 Red Hat Linux 上的标准工具随机化文件中的行?

python - 在 Python 脚本中,如何设置 PYTHONPATH?

python - 如何以正确的方式平滑曲线?

linux - CURL 用于访问需要从其他页面登录的页面