首页 > 解决方案 > 声明方法参数类型列表的最佳方式

问题描述

我知道放置参数类型列表的好方法是:

def test(my_list = None):
    if my_list is None:
        my_list = []

但我不明白为什么我不能简单地做这样的事情:

def test(my_list = list)

我在控制台模式下尝试过并且可以工作

更新

在“最小惊讶”和可变默认参数中,他们解释了为什么我们不应该使用

def test(my_list = [])

不是为什么我不能使用

def test(my_list = list)

标签: pythonpython-3.x

解决方案


如果你这样做l=list,你会得到这个错误:

def a(l=list):
    print([x for x in l])
a()

# >> TypeError: 'type' object is not iterable

你要做的是def a(l=list()),这与def a(l=[]).

然后我们回到这里的问题:“Least Astonishment” and the Mutable Default Argument

更新

如果我理解你,为什么不简单地做:

def a(l=[]):
    l = l or []
    # ...rest of the method

推荐阅读