为什么我可以在ipython命令行上修改这个列表,但不能在函数中修改?

2024-06-12 03:04:02 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的疑问是related to this question,但有点不同。答案我不清楚

考虑一个必须修改的列表x。下面的ipython会话说明了这一点:

In [1]: x=[]
In [2]: x.append(2)
In [3]: x
Out[3]: [2]
In [4]: x=[] # able to start working on x again
In [5]: x
Out[5]: []

In [6]: def modify(x):
   ...:     x.append(2)
   ...:     print x
   ...:     x=[]   # does not throw errors
   ...:     

In [7]: x=[]
In [8]: x.append(2)

In [9]: x.append(2)
In [10]: x    # x is now a list
Out[10]: [2, 2]

In [11]: modify(x)    # len(s) proportional to the number of times modify is called
[2, 2, 2]

In [12]: x
Out[12]: [2, 2, 2]

如果x,列表是一个可变的对象,为什么我不能在函数中修改它,但是可以在命令行中修改它?我认为这与函数是main有关,但是:

  In [30]: def modify(x):
      ...:     print __name__
      ...:     x.append(2)
      ...:     print x
      ...:     x=[]
      ...:     x=[1, 5, 7]
      ...:     

下面的会话显示名称保持不变

  In [36]: print __name__
  __main__

  In [37]: x=[]

  In [38]: modify(x)
  __main__
   [2]
  # why is the name __main__ inside modify?
  In [39]: modify(x)
  __main__
  [2, 2]

Tags: theto函数namein列表ismain