繁体   English   中英

Python TypeError: got an unexpected keyword argument 'name'

[英]Python TypeError: got an unexpected keyword argument 'name'

我是 python 的新手,最近我刚刚学习了 *args 和 **kwargs 的基础知识。

当我尝试使用自己的代码进行练习时,出现了一个意想不到的关键字错误,如下所示:

def student_info2(args, kwargs):
    print(args)
    print(kwargs)

courses = ["Maths", "Statistics"]
module = "Data Science"
students = {"name": "John Price", "age": 27}
welcome_words = {"welcome": "hello and welcome"}
student_info2(*courses, *module, **students, **welcome_words)
TypeError                                 Traceback (most recent call last)
<ipython-input-61-8bc2f643a250> in <module>
      7 students = {"name":"John Price","age":27}
      8 welcome_words = {"welcome":"hello and welcome"}
----> 9 student_info2(*courses,*module, **students, **welcome_words)

TypeError: student_info2() got an unexpected keyword argument 'name'

我真的不知道为什么会这样,如果有人可以帮助我解决这个问题,我真的很感激。

def student_info2(args,kwargs):
    print(args)
    print(kwargs)

这个 function 可以正常工作,但仅限于 2 个 arguments 即argskwargs 此时argskwargs只是 2 个变量名称,它们不会按照您的意愿行事,因为您没有将它们与*args**kwargs之类的解包运算符一起使用。

*args**kwargs用于为 function 提供不同数量的输入 arguments。 argskwargs只是一个变量名,可以更改为您需要的任何名称。

def student_info2(*args, **kwargs):
    print(args)
    print(kwargs)

笔记:

  • *args接受迭代或位置 arguments 和**kwargs接受关键字或命名 arguments。
  • 定义 function 参数时, *args必须在**kwargs之前。

你不需要 *s,你应该把它们放在你的 function 的声明中。 此外,如果您给 function 4 个参数,您应该收到 4 个。

def student_info2(arg1, arg2, arg3, arg4):
    print(arg1)
    print(arg2)
    print(arg3)
    print(arg4)
    

courses = ["Maths","Statistics"]
module = "Data Science"
students = {"name":"John Price","age":27}
welcome_words = {"welcome":"hello and welcome"}
student_info2(courses, module, students, welcome_words)

如果你想接收 X 数量的参数,你应该这样做

def student_info2(*args):
    print(args)
    

courses = ["Maths","Statistics"]
module = "Data Science"
students = {"name":"John Price","age":27}
welcome_words = {"welcome":"hello and welcome"}
student_info2(courses, module, students, welcome_words)

其中args将是参数列表。 **kwargs将是字典而不是列表。 您也可以混合使用普通参数和 args/kwargs。

检查此站点以获取更多说明: https://www.geeksforgeeks.org/args-kwargs-python/

你在这里做错的是

您的 function student_info2 只能通过您的代码获取 2 个位置 arguments,因此您应该像这样调用 function

student_info2(课程,模块)

如果您希望在一个 go 中调用所有 4 个,那么您的 function 声明应该像这样

student_info2(arg1, arg2, arg3, arg4) 或 student_info2(*args)

您有两个参数作为 function 的输入,但您给了四个 arguments 作为 function 的输入,但如果您不想使用 args 和 kwargs,请使用这种方式。 看看这些网站,他们可以帮助你理解

https://realpython.com/python-kwargs-and-args/

https://www.programiz.com/python-programming/args-and-kwargs

https://www.geeksforgeeks.org/args-kwargs-python/

暂无
暂无

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

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