将列表/字典作为参数传递给函数与直接在函数中修改它相比,有什么优点/缺点吗?

  • 本文关键字:函数 缺点 参数传递 字典 列表 修改 python
  • 更新时间 :
  • 英文 :


这样做有什么好处或缺点

listtt =[1]
dicto = {'a':2}
def ffun():
listtt.append(2)
dicto['b'] = 3
ffun()
print(listtt)
print(dicto)

[1, 2] {'a': 2, 'b': 3}

与这个

listtt =[1]
dicto = {'a':2}
def ffun(hh, hh2):
hh.append(2)
hh2['b'] = 3
ffun(listtt, dicto)
print(listtt)
print(dicto)

[1, 2] {'a': 2, 'b': 3}

*嗨,

我可能过于简化了这一点,但即使以非常高的数量传递字典和列表,您那里的内容也不会引起任何问题。Python 通过对象引用传递参数,因此没有内存操作,两种情况下的性能应该相同。 话虽如此,您仍然需要重新考虑为什么要首先使用全局变量。Kaya已经在评论中链接了围绕全局变量的讨论。值得快速阅读*

最新更新