首頁  >  文章  >  後端開發  >  在Python中,函數參數清單中的斜線(/)表示分隔位置參數和關鍵字參數的界限

在Python中,函數參數清單中的斜線(/)表示分隔位置參數和關鍵字參數的界限

WBOY
WBOY轉載
2023-08-26 14:13:052228瀏覽

A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Let us first see a function in Python with a parameter −

Function in Python

Example

在這裡,我們正在使用參數myStr在Python中創建一個基本函數 -

# Creating a Function
def demo(myStr):
   print("Car =: ",myStr)

# function call
demo("BMW")
demo("Tesla")

輸出

Car =: BMW
Car =: Tesla

Slash in the parameter list of a function

如上所述,函數參數清單中的斜線表示其先前的參數是僅位置參數。

在呼叫接受僅位置參數的函數時,參數將僅根據它們的位置進行映射。

divmode()函數

divmod() 函數是一個函數清單中斜線的完美範例,即它接受位置參數,如下所示 −

divmod(a, b, /)

上面,由於斜線位於參數清單的結尾,因此參數a和b都是位置參數。

Let us print the documentation of divmod() using the help() functiojn in Python

# Creating a Function
def demo(myStr):
   print(help(divmod))

# function call
demo("BMW")
demo("Tesla")

輸出

Help on built-in function divmod in module builtins:

divmod(x, y, /)
   Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
None

Now, let us see an example of the divmod(). Both the parameters are dividend and divisor −

k = divmod(5, 2)

print(k)

輸出

(2, 1)

參數清單末端的斜線表示兩個參數都是位置參數。因此,如果我們使用關鍵字參數呼叫divmod(),將會引發錯誤 −

divmod(a = 5, b = 2)

輸出

在Python中,函數參數清單中的斜線(/)表示分隔位置參數和關鍵字參數的界限

#In the above example, an error occurred since the divmod() takes no keyword arguments.

以上是在Python中,函數參數清單中的斜線(/)表示分隔位置參數和關鍵字參數的界限的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除