好的,这是我的代码:
class foo():
def x(self, arg = []):
print arg
if len(arg):
print "arg already contains data"
arg.append("one call were made")
非常简单。我可以将列表作为参数传递,但是,如果我没有通过它,我会为我生成一个全新的,好吗?
但是看看当我调用该方法两次时会发生什么:
>>> ob = foo()
>>> ob.x()
[]
>>> ob.x()
['one call were made']
arg already contains data
>>> ob.x()
['one call were made', 'one call were made']
arg already contains data
这对我来说似乎很直观。我最初的想法是,列表将在函数调用中生成,当函数结束时,将使用本地作用域的其余部分销毁。
发生了什么事?为什么会这样?在哪里存储列表的状态?