Python中默认参数的范围是什么? [英] What is the scope of a defaulted parameter in Python?

查看:95
本文介绍了Python中默认参数的范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您在Python中使用数组参数定义函数时,该参数的范围是什么?

此示例摘自Python教程:

def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
print f(3)

打印:

[1]
[1, 2]
[1, 2, 3]

我不确定我是否了解这里发生的事情.这是否意味着数组的范围不在函数范围之内?为什么数组在每次调用时都记住其值?来自其他语言,只有在变量为静态的情况下,我才会期望这种行为.否则,似乎应该每次都将其重置.实际上,当我尝试以下操作时:

def f(a):
    L = []
    L.append(a)
    return L

我得到了预期的行为(每次调用都重置了数组).

所以在我看来,我只需要解释def f(a, L=[]):行-L变量的范围是什么?

解决方案

范围与您期望的一样.

也许令人惊讶的是,默认值仅计算一次并重新使用,因此每次调用该函数时,您将获得相同的列表,而不是初始化为[]的新列表.

列表存储在f.func_defaults中.

def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
print f(3)
print f.func_defaults
f.func_defaults = (['foo'],) # Don't do this!
print f(4)

结果:

[1]
[1, 2]
[1, 2, 3]
([1, 2, 3],)
['foo', 4]

When you define a function in Python with an array parameter, what is the scope of that parameter?

This example is taken from the Python tutorial:

def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
print f(3)

Prints:

[1]
[1, 2]
[1, 2, 3]

I'm not quite sure if I understand what's happening here. Does this mean that the scope of the array is outside of the function? Why does the array remember its values from call to call? Coming from other languages, I would expect this behavior only if the variable was static. Otherwise it seems it should be reset each time. And actually, when I tried the following:

def f(a):
    L = []
    L.append(a)
    return L

I got the behavior I expected (the array was reset on each call).

So it seems to me that I just need the line def f(a, L=[]): explained - what is the scope of the L variable?

解决方案

The scope is as you would expect.

The perhaps surprising thing is that the default value is only calculated once and reused, so each time you call the function you get the same list, not a new list initialized to [].

The list is stored in f.func_defaults.

def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
print f(3)
print f.func_defaults
f.func_defaults = (['foo'],) # Don't do this!
print f(4)

Result:

[1]
[1, 2]
[1, 2, 3]
([1, 2, 3],)
['foo', 4]

这篇关于Python中默认参数的范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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