我四處搜索,發現this article,這讓我領先了解爲什麼會發生這種情況 - 看來我剛剛遇到了一個更復雜,更微妙的情況。但這些微妙之處讓我感到困惑,並尋求更清晰的解釋。 (我懷疑它的事項,但以防萬一:我使用的是Windows 7中的Python 2.7.x)Python:爲什麼類方法中的本地列表變量保留其值?
的出發點是該位的代碼,這是我從一個更大,更復雜的應用蒸餾水在哪裏首先遇到問題。
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
操縱呢?
[可變的默認參數。](http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments) – user2357112