python - 声明方法参数类型列表的最佳方式
问题描述
我知道放置参数类型列表的好方法是:
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)
解决方案
如果你这样做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
推荐阅读
- php - 如何使用操作或过滤器更新 WordPress 中的元标记?
- python - 如何为字典变量设置 python 类型提示?
- css - 使用 custom.css 进行引导覆盖
- java - 带有配置文件的 Spring Boot:找不到 javax.sql.DataSource'
- typescript - 如何在角度 6 的 mat-nav-list 中设置活动项目的颜色
- javascript - 如何在 TypeScript 中定位 ES2018?
- asp.net - Asp net,将原始 h264 流式传输到浏览器
- java - 为什么我无法连接到服务器?
- c++ - 我应该如何在没有变量的情况下将相同的参数传递给 CMAKE 中的多个目标?
- caffe2 - Caffe2:安装densepose时使操作失败