相关疑难解决方法(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函数默认参数只评估一次?

我是一个python初学者,阅读'python tutorial',它说如果我们有一个函数:

def f(a, L=[]):
     L.append(a)
     return L
print f(1)
print f(2)
print f(3)
Run Code Online (Sandbox Code Playgroud)

这将打印

[1]
[1, 2]
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

因为默认值只计算一次而list是可变对象.我能理解.

它说继续,如果我们不希望在后续调用之间共享默认值,我们可以:

def f(a, L=None):
   if L is None:           #line  2
       L = []            
   L.append(a)
   return L
print f(1)            
print f(2)
print f(3)
Run Code Online (Sandbox Code Playgroud)

这将输出:

[1]
[2]
[3]
Run Code Online (Sandbox Code Playgroud)

为什么呢?怎么解释这个.我们知道默认值只是被评估once,当我们调用f(2)时,L不是None而且if(第2行)不能为真,所以L.append(a)== [1,2].我可以猜出由于某种原因再次评估默认值,但是什么是'某种原因',只是因为python解释器看到了if L is None: L = []

python parameters function

30
推荐指数
3
解决办法
4908
查看次数

标签 统计

python ×2

function ×1

parameters ×1