簡體   English   中英

位置參數跟在關鍵字參數之后| 調用函數時出錯

[英]Positional argument follows keyword argument | Error while calling function

首先,我了解到,在定義函數時,您必須先放置位置參數,然后放置默認參數,以避免解釋程序出現歧義。 這就是為什么當我們嘗試這樣做時會引發錯誤。

例如,在以下代碼中,a和b不能在運行時求值,因為它會引發錯誤

def func(a=1,b):
    return a+b

func(2)

Error:non-default argument follows default argument

這是可以理解的。

但是,為什么以下導致錯誤。 它不是在定義函數時發生的,而是在調用函數時發生的。

def student(firstname, standard,lastname): 
    print(firstname, lastname, 'studies in', standard, 'Standard') 
student(firstname ='John','Gates','Seventh')

Error:positional argument follows keyword argument

我們不能同時傳遞帶有關鍵字和不帶有關鍵字的參數嗎? [編輯]:問題不是可能的重復項,因為重復項討論了定義默認參數的情況。 我還沒有定義它們。 我只是問為什么我們不能混合使用關鍵字值參數和直接值參數。

正如錯誤所言:

Error:positional argument follows keyword argument

關鍵字參數后不能有位置參數。

您的示例就是一個很好的例子。

您將第一個參數指定為關鍵字參數。 因此,現在解釋器如何解釋參數順序是不明確的。 第二個參數是否成為第一個參數? 第二個參數? 但是您已經指定了第一個參數( firstname='John' ),那么位置參數會發生什么?

def學生(名字,標准,姓氏):打印(名字,姓氏,“學習”,標准,“標准”)

student(firstname ='John','Gates','Seventh')

解釋是否解釋為:

student(firstname ='John',standard='Gates',lastname='Seventh')

要么

student(firstname ='John',standard='Gates',lastname='Seventh')

要么

student(firstname ='John',firstname='Gates',lastname='Seventh')

關於什么:

student(lastname ='John','Gates','Seventh')

這個?

student(lastname ='John',firstname='Gates',standard='Seventh')

或這個?

student(lastname ='John',standard='Gates',firstname='Seventh')

嘗試調試與參數匹配的參數的好運。

也許您應該嘗試:

student('John', 'Gates', 'Stevehn')

我不知道您是否可以在調用函數的同時定義變量。

悉尼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM