【发布时间】:2020-01-26 14:28:41
【问题描述】:
如何将函数的可选参数设置为列表?
def fun1(text, where = my_list):
#my_list.append(text)
where.append(text)
print(where)
#return where
my_list = []
fun1('hi')
print(my_list)
# currently
#['hi']
#[]
# expected
#['hi']
#['hi']
我在 Spyder 中收到未定义名称 my_list 错误。
【问题讨论】:
-
你不想想要这样做。 stackoverflow.com/questions/1132941/…
-
将此行
my_list = []放在您的def之前。但是您应该避免将可变参数作为默认参数,这是 python 中非常常见的“陷阱” -
这是非常糟糕的架构解决方案,不要那样做。
-
为什么设计视角不好?如果我调用函数 m 次和 n 次它与 my_list 相关,其中 n 接近 m,这是否有意义?
标签: python list function arguments optional-arguments