Python 类型错误:get() 不接受关键字参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24463202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:39:12  来源:igfitidea点击:

TypeError: get() takes no keyword arguments

python

提问by itsmichaelwang

I'm new at Python, and I'm trying to basically make a hash table that checks if a key points to a value in the table, and if not, initializes it to an empty array. The offending part of my code is the line:

我是 Python 新手,我正在尝试制作一个哈希表,用于检查键是否指向表中的值,如果没有,则将其初始化为空数组。我的代码有问题的部分是这一行:

converted_comments[submission.id] = converted_comments.get(submission.id, default=0)

I get the error:

我收到错误:

TypeError: get() takes no keyword arguments

But in the documentation (and various pieces of example code), I can see that it does take a default argument:

但是在文档(以及各种示例代码)中,我可以看到它确实采用了默认参数:

https://docs.python.org/2/library/stdtypes.html#dict.gethttp://www.tutorialspoint.com/python/dictionary_get.htm

https://docs.python.org/2/library/stdtypes.html#dict.get http://www.tutorialspoint.com/python/dictionary_get.htm

Following is the syntax for get() method:

dict.get(key, default=None)

以下是 get() 方法的语法:

dict.get(key, 默认=无)

There's nothing about this on The Stack, so I assume it's a beginner mistake?

The Stack 上没有这方面的内容,所以我认为这是初学者的错误?

采纳答案by GWW

The error message says that gettakes no keyword arguments but you are providing one with default=0

错误消息说get没有关键字参数,但您提供了一个default=0

converted_comments[submission.id] = converted_comments.get(submission.id, 0)

回答by user2357112 supports Monica

Due to the way the Python C-level APIs developed, a lot of built-in functions and methods don't actually have names for their arguments. Even if the documentation calls the argument default, the function doesn't recognize the name defaultas referring to the optional second argument. You have to provide the argument positionally:

由于 Python C 级 API 的开发方式,许多内置函数和方法实际上并没有为其参数命名。即使文档调用了 argument default,该函数也不会将该名称识别default为引用可选的第二个参数。您必须按位置提供参数:

>>> d = {1: 2}
>>> d.get(0, default=0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: get() takes no keyword arguments
>>> d.get(0, 0)
0