相关疑难解决方法(0)

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

我正在尝试理解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()
Run Code Online (Sandbox Code Playgroud)

输出:

Before: 1 [0, 1, 2, 3]
In f(): 2 [0, 1, 2, 3, 4]
After:  1 [0, 1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

python

167
推荐指数
5
解决办法
12万
查看次数

标签 统计

python ×1