我是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'
我真的不知道为什么会这样,如果有人可以帮助我解决这个问题,我将不胜感激。
答案 0 :(得分:1)
def student_info2(args,kwargs):
print(args)
print(kwargs)
该函数可以正常工作,但仅限于2个参数,即args
和kwargs
。此时,args
和kwargs
只是2个变量名称,它们将无法按您的预期作用,因为您尚未将它们与*args
和{{1}这样的解包运算符一起使用}。
**kwargs
和*args
用于为函数提供不同数量的输入参数。
**kwargs
,args
只是一个变量名称,可以将其更改为所需的任何名称。
kwargs
注意:
def student_info2(*args, **kwargs):
print(args)
print(kwargs)
接受可迭代项或位置参数,并且*args
接受关键字或命名参数。**kwargs
必须位于*args
之前。答案 1 :(得分:0)
您在那里不需要*,应该将它们放在函数的声明中。同样,如果给函数提供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/
答案 2 :(得分:0)
您在这里做错了什么
您的函数Student_info2在您的代码中只能接受2个位置参数,因此您应该像这样调用该函数
student_info2(课程,模块)
如果您希望一次调用所有4个,则您的函数声明应如下所示
student_info2(arg1,arg2,arg3,arg4)或student_info2(* args)
答案 3 :(得分:0)
您有两个参数作为函数的输入,但是给了四个参数作为函数的输入,但是如果要使用args和kwargs,则不应使用这种方式。 看到这些网站,它们可以帮助您理解
https://realpython.com/python-kwargs-and-args/
https://www.programiz.com/python-programming/args-and-kwargs