Python命名参数范围有一个默认列表值,这会让人困惑
我对下面示例中使用的names参数的范围感到困惑Python命名参数范围有一个默认列表值,这会让人困惑,python,Python,我对下面示例中使用的names参数的范围感到困惑 def disp( p1, list=[] ): list.append( p1 ) return list list1 = disp( 10 ) list2 = disp( 123 ) list3 = disp( 'a' ) print ( list1 ) print ( list2 ) print ( list3 ) 输出为 [10, 123, 'a'] [10, 123, 'a'] [10, 123, 'a'] 我
def disp( p1, list=[] ):
list.append( p1 )
return list
list1 = disp( 10 )
list2 = disp( 123 )
list3 = disp( 'a' )
print ( list1 )
print ( list2 )
print ( list3 )
输出为
[10, 123, 'a']
[10, 123, 'a']
[10, 123, 'a']
我们如何解释变量列表的范围,它是函数定义中的命名参数?
如果不是列表,而是其他的东西,比如整数,它的工作方式就不同了
def disp2( p1, myVal = 0 ):
myVal += myVal + p1
return myVal
v1 = disp2(9)
v2 = disp2(7)
v3 = disp2(77)
print ( v1, v2, v3 )
想法?我想了解第一个示例背后的细节(通过更改代码很容易避免它)。在Python中,某些类型是不可变的(
str
,int
,等等),而其他类型是可变的(list
,dict
,tuple
,等等)
您的代码的行为与此类似,因为您将默认参数设置为mutable类型(list=[]
),它返回的结果是相同的对象,但具有不同的(更新的)值(内容)
了解这种行为以及如何潜在地解决它可能是一本很好的读物
函数运行时,Python的默认参数将计算一次
已定义,而不是每次调用函数时。这意味着如果您使用可变的默认参数
对其进行变异,您将对该对象进行变异,并在以后的所有调用中对其进行变异
对功能也有影响
默认值只分配一次 您没有复制列表,只是添加了另一个键变量来访问它,所以在本例中,它们都是相同的列表 这样做吧
def disp( p1, list = None ):
if list is None: # None is nothing
list = []
list.append( p1 )
return list
# here you don't need to copy since there different lists
# unlike then
list1 = disp( 10 )
list2 = disp( 123 )
list3 = disp( 'a' )
print ( list1 )
print ( list2 )
print ( list3 )
输出将是
[ 10 ]
[ 123 ]
[ 'a' ]
你可以像这样复制列表
list = Original.copy() # now those will be fundamentally different lists but same values
list = [i for i in Original]
还是像这样
list = Original.copy() # now those will be fundamentally different lists but same values
list = [i for i in Original]