您不能使用列表作为默认参数,但您可以使用元组吗?

问题描述

请让我知道是否有帖子已经解决了这个问题,我无法找到有关此特定主题的具体答案。

您不应该使用列表作为函数参数的默认值,因为它是可变的。在这种情况下,以下哪个代码是最佳实践?

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']

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...