【问题标题】:please explain how python executes the following code: [duplicate]请解释python如何执行以下代码:[重复]
【发布时间】:2018-11-17 01:44:39
【问题描述】:

我对以下代码生成的输出很感兴趣。 谁能向我解释为什么 python 在第三次执行函数调用时打印 [1,5] 而不仅仅是 [5],以及它是 Python 中的功能还是错误?

def funn(arg1, arg2=[]):
    arg2.append(arg1)
    print(arg2)
funn(1)
funn(2, [3, 4])
funn(5)

【问题讨论】:

  • 我相信是因为arg2在第一次被调用时只被赋予了默认值(空数组)。然后任何不提供值的后续调用将使用最初创建的相同实例。所以第 3 次调用将使用第一次调用中创建的数组,该数组已经附加了1

标签: python function scope namespaces interpreter


【解决方案1】:

有一篇关于这个here 的好文章。但为了更好地理解,我对你的函数做了一个小的修改,以更好地可视化问题。

def funn(arg1, arg2=[]):
    print(id(arg2))
    arg2.append(arg1)
    print(arg2)
funn(1) # here you will get printed an id of arg2
funn(2, [3, 4]) # here it's a different id of arg2 because it's a new list
funn(5) # here you will see that the id of the arg2 is the same as in the first function call.

【讨论】:

  • 谢谢都铎王朝。这很有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-19
  • 2016-01-02
  • 1970-01-01
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
相关资源
最近更新 更多