最近在看《Python语言及其应用》这本书,里面提到了函数调用的一个坑,没有搞懂是怎么回事,求教一下。
先看代码和输出吧
def buggy(arg, result=[]):
result.append(arg)
print(result)
def work(arg):
result = []
result.append(arg)
return result
def nonbuggy(arg, result=[]):
if result is None:
result = []
result.append(arg)
return result
def test(arg, result=[]):
result.append(arg)
return result
print('---buggy---')
buggy('a')
buggy('b')
print('---work---')
print(work('a'))
print(work('b'))
print('---nonbuggy---')
print(nonbuggy('a'))
print(nonbuggy('b'))
print('---test---')
print(test('a'))
print(test('b'))
输出
---buggy---
['a']
['a', 'b']
---work---
['a']
['b']
---nonbuggy---
['a']
['b']
---test---
['a']
['a', 'b']
不明白为什么buggy()
和test()
函数得到的结果会受到之前调用的影响。这是不是和python
的内存模型有关系?
PHP中文网2017-04-18 09:43:22
Default parameter value result = [] has been created during the definition period, and result points to the same object every time it is executed