寶慕林4294392
2021-08-24 15:11:45
首先,我明白在定義函數(shù)時,您必須先放置位置參數(shù),然后再放置默認(rèn)參數(shù),以避免解釋器出現(xiàn)歧義情況。這就是為什么當(dāng)我們嘗試這樣做時,它會拋出錯誤。例如,在以下代碼中,無法在運行時評估 a 和 b,因為它會引發(fā)錯誤def func(a=1,b): return a+bfunc(2)( Error:non-default argument follows default argument)這是可以理解的。但是為什么以下會導(dǎo)致錯誤。它不是在定義函數(shù)時發(fā)生,而是在調(diào)用函數(shù)時發(fā)生。def student(firstname, standard,lastname): print(firstname, lastname, 'studies in', standard, 'Standard') student(firstname ='John','Gates','Seventh')Error:positional argument follows keyword argument我們不能同時傳遞帶關(guān)鍵字和不帶關(guān)鍵字的參數(shù)嗎?[編輯]:問題不是可能的重復(fù)項,因為重復(fù)項涉及定義默認(rèn)參數(shù)的情況。我沒有定義它們。我只是問為什么我們不能混合關(guān)鍵字值參數(shù)和直接值參數(shù)。
2 回答

ibeautiful
TA貢獻(xiàn)1993條經(jīng)驗 獲得超6個贊
就像錯誤所說的那樣:
Error:positional argument follows keyword argument
關(guān)鍵字參數(shù)后面不能有位置參數(shù)。
你的例子就是一個很好的例子。
您將第一個參數(shù)指定為關(guān)鍵字參數(shù)。所以解釋器現(xiàn)在如何解釋參數(shù)的順序是不明確的。第二個參數(shù)是否成為第一個參數(shù)?第二個參數(shù)?但是您已經(jīng)指定了第一個參數(shù) ( firstname='John'
) 那么位置參數(shù)會發(fā)生什么?
def student(firstname, standard,lastname): print(firstname, lastname, 'studies in', standard, 'Standard')
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')
祝你在調(diào)試什么參數(shù)匹配什么參數(shù)時好運。

茅侃侃
TA貢獻(xiàn)1842條經(jīng)驗 獲得超22個贊
也許你應(yīng)該嘗試:
student('John', 'Gates', 'Stevehn')
我不知道你是否可以在調(diào)用函數(shù)的同時定義一個變量。
悉尼
添加回答
舉報
0/150
提交
取消