Python - 3.8 新特性之僅位置參數 & 僅關鍵字參數


前置知識

Python 函數:https://www.cnblogs.com/poloyy/p/15092393.html

 

什么是僅限位置形參

  • 僅限位置形參是 Python 3.8 才有的新特性
  • 新增了一個函數形參語法 /
  • 添加了它,表示函數形參只能通過位置參數傳遞,而不能通過關鍵字參數形式傳遞

 

僅限位置形參栗子

def test1(a, b, c):
    print(a, b, c)


test1(a=1, b=2, c=3)


def test(a, /, b, c):
    print(a, b, c)


# 正確
test(1, b=2, c=3)
test(*(1,), b=2, c=3)

# 錯誤
test(a=1, b=2, c=3)


1 2 3
1 2 3
1 2 3

    test(a=1, b=2, c=3)
TypeError: test() got some positional-only arguments passed as keyword arguments: 'a'
  • 報錯信息:test() 得到一些作為關鍵字參數傳遞的僅位置參數 ‘a'
  • 在 / 形參的參數只能通過位置參數傳遞

 

什么是僅限關鍵字參數

  • 和僅位置參數一樣,也是 Python 3.8 的新特性
  • 參數只傳 * 代表僅關鍵字參數
  • 添加了它,表示函數形參只能通過關鍵字參數傳遞,而不能通過位置參數傳遞

 

 僅限關鍵字參數栗子

def f1(a, *, b, c):
    return a + b + c


# 正確
f1(1, b=2, c=3)
f1(1, **{"b": 2, "c": 3})

# 錯誤
f1(1, 2, c=3)


# 輸出結果
6
6

    f1(1, 2, c=3)
TypeError: f1() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given 
  • 報錯信息:接受1個位置參數,但提供了2個位置參數(和1個僅限關鍵字的參數)
  • 在 * 形參的參數只能通過關鍵字參數傳遞

 

/ 和 * 混合栗子

def f(a, /, b, *, c):
    print(a, b, c)


# 正確
f(1, 2, c=3)
f(1, b=2, c=3)

# 錯誤
f(a=1, b=2, c=3)
f(1, 2, 3)


# 輸出結果
1 2 3
1 2 3

 

栗子二

def f(a, b, /, c, *, d, e):
    print(a, b, c, d, e)


# 正確
f(1, 2, c=3, d=4, e=5)

# 錯誤
f(1, 2, 3, 4, 5)

# 輸出結果
1 2 3 4 5 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM