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