简体   繁体   English

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

[英]TypeError: get() takes no keyword arguments

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.我是 Python 新手,我正在尝试制作一个哈希表,用于检查键是否指向表中的值,如果没有,则将其初始化为空数组。 The offending part of my code is the line:我的代码有问题的部分是这行:

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.get http://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:以下是 get() 方法的语法:

dict.get(key, default=None) dict.get(key, 默认=无)

There's nothing about this on The Stack, so I assume it's a beginner mistake? The Stack 上没有这方面的内容,所以我认为这是初学者的错误?

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.由于 Python C 级 API 的开发方式,许多内置函数和方法实际上并没有为其参数命名。 Even if the documentation calls the argument default , the function doesn't recognize the name default as referring to the optional second argument.即使文档调用参数default ,该函数也不会将名称default识别为引用可选的第二个参数。 You have to provide the argument positionally:您必须按位置提供参数:

>>> 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

错误消息说get接受关键字参数,但您提供的参数为default=0

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

Many docs and tutorials, for instance https://www.tutorialspoint.com/python/dictionary_get.htm , erroneously specify the syntax as许多文档和教程,例如https://www.tutorialspoint.com/python/dictionary_get.htm ,错误地将语法指定为

dict.get(key, default = None)

instead of代替

dict.get(key, default)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM