我四处搜寻并找到了这篇文章,它为我提供了为什么发生这种情况的线索-看来我只是遇到了一个更复杂,更微妙的案例。但是那些微妙之处使我感到困惑,并寻求更清晰的解释。(我怀疑这是否重要,但以防万一:我在Windows 7上使用Python2.7.x。)
起点是这段代码,我从一个更大,更复杂的应用程序中提炼出了我最初遇到的问题。
class MyClass():
def printStuff(self,myList=[1,2,3],myInt=4):
print '--------------------------------'
print 'myList at start: '+str(myList)
print 'myInt at start: '+str(myInt)
doNotCare = myList.pop()
myInt = myInt - 1
print 'myList at end: '+str(myList)
print 'myInt at end: '+str(myInt)
testMC = MyClass()
testMC.printStuff()
testMC.printStuff()
testMC.printStuff()
...将产生以下输出:
--------------------------------
myList at start: [1, 2, 3]
myInt at start: 4
myList at end: [1, 2]
myInt at end: 3
--------------------------------
myList at start: [1, 2]
myInt at start: 4
myList at end: [1]
myInt at end: 3
--------------------------------
myList at start: [1]
myInt at start: 4
myList at end: []
myInt at end: 3
现在,基于有关如何在函数中处理默认参数的各种文章,似乎myInt
应该表现出与相同的行为myList
,即应将其递减为3、2、1。但是显然不是。
如果我修改该doNotCare = myList.pop()
行,而不是使用切片来更新列表,则难题会变得更加复杂:
class MyClass():
def printStuff(self,myList=[1,2,3],myInt=4):
print '--------------------------------'
print 'myList at start: '+str(myList)
print 'myInt at start: '+str(myInt)
myList = myList[:-1]
myInt = myInt - 1
print 'myList at end: '+str(myList)
print 'myInt at end: '+str(myInt)
testMC = MyClass()
testMC.printStuff()
testMC.printStuff()
testMC.printStuff()
...以某种方式击败了那个意外的保留值,产生了输出:
--------------------------------
myList at start: [1, 2, 3]
myInt at start: 4
myList at end: [1, 2]
myInt at end: 3
--------------------------------
myList at start: [1, 2, 3]
myInt at start: 4
myList at end: [1, 2]
myInt at end: 3
--------------------------------
myList at start: [1, 2, 3]
myInt at start: 4
myList at end: [1, 2]
myInt at end: 3
因此,我想第一个问题是,实际上这只是参考文献中描述的默认参数行为的更复杂,更微妙的情况吗?如果是这样,那么当我用切片而不是切片操作时,该行为为何不适用于myInt
-甚至什至不适用?myList
pop
与列表不同,数字是不可变的,因此不能更改。可以重新分配对它们的引用,但是1始终是1。
拼接不会产生此行为,因为它会创建原始副本,而pop
修改原始列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句