【问题标题】:Set optional argument of function to list [duplicate]将函数的可选参数设置为列表 [重复]
【发布时间】: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


【解决方案1】:

你应该使用 **kwargs 在你的函数中设置任何意想不到的参数。并使用 kwargs['where'] 来实现'where'键,像这样:

def fun1(text, **kwargs):
    kwargs['where'].append(text)
    print(kwargs['where'])

my_list = []
fun1('hi',where=my_list)
print(my_list)

【讨论】:

  • 我想避免使用 my_list 调用 fun1。
【解决方案2】:

我认为你应该像这样在你的函数之前定义你的列表:

my_list = []
def fun1(text, where = my_list):
  #my_list.append(text)
  where.append(text)
  print(where)
  #return where
fun1('hi')

如果您想打印一次,请不要使用 print(my_list)。您将其打印为 fun1() 内部的位置

【讨论】:

  • 这不会永久附加 my_list,即在乐趣之外。
猜你喜欢
  • 2019-09-23
  • 2010-11-21
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
  • 2013-02-28
  • 1970-01-01
  • 2013-06-24
相关资源
最近更新 更多