问题描述
请让我知道是否有帖子已经解决了这个问题,我无法找到有关此特定主题的具体答案。
您不应该使用列表作为函数参数的默认值,因为它是可变的。在这种情况下,以下哪个代码是最佳实践?
def my_func(arg1 = ("hello","world")):
pass
或
def my_func(arg1 = None):
if arg1 is None:
arg1 = ["hello","world"]
我说的是元组和列表可以在函数内部以相同方式使用的情况。
谢谢!
解决方法
取决于你是否想改变它:
对于元组:
def my_func(arg1 = ("hello","world")):
arg1[0] = "other val"
你会得到 --> TypeError: 'tuple' object does not support item assignment
如上所述,列表是可变的:
def my_func(arg1 = None):
if arg1 is None:
arg1 = ["hello","world"]
arg1[0] = "other val"
arg1
是 ['other val','world']