Python - 預設引數



Python 預設引數

Python 允許為一個或多個形式引數分配**預設值**來定義函式。如果未向引數傳遞任何值,Python 將使用該引數的預設值。如果傳遞任何值,則預設值將被傳遞的實際值覆蓋。

Python 中的預設引數是指在不向函式呼叫傳遞任何引數時將使用的函式引數。

預設引數示例

以下示例顯示了 Python 預設引數的使用。此處,對函式的第二次呼叫不會向"city" 引數傳遞值,因此將使用其預設值"Hyderabad"

# Function definition 
def showinfo( name, city = "Hyderabad" ):
   "This prints a passed info into this function"
   print ("Name:", name)
   print ("City:", city)
   return

# Now call showinfo function
showinfo(name = "Ansh", city = "Delhi")
showinfo(name = "Shrey")

它將產生以下**輸出** -

Name: Ansh
City: Delhi
Name: Shrey
City: Hyderabad

示例:不使用關鍵字引數呼叫函式

讓我們來看另一個例子,它為函式引數分配預設值。函式percent() 有一個名為"maxmarks" 的預設引數,其設定為 200。因此,在呼叫函式時,我們可以省略第三個引數的值。

# function definition 
def percent(phy, maths, maxmarks=200):
   val = (phy + maths) * 100/maxmarks
   return val

phy = 60
maths = 70
# function calling with default argument
result = percent(phy, maths)
print ("percentage:", result)

phy = 40
maths = 46
result = percent(phy, maths, 100)
print ("percentage:", result)

執行此程式碼後,將產生以下輸出 -

percentage: 65.0
percentage: 86.0

可變物件作為預設引數

Python 在定義函式時只評估一次預設引數,而不是每次呼叫函式時都評估。因此,如果您使用可變預設引數並在給定函式中對其進行修改,則在後續函式呼叫中將引用相同的值。

可以在建立後更改的 Python 物件稱為可變物件。

示例

以下程式碼解釋瞭如何在 Python 中使用可變物件作為預設引數。

def fcn(nums, numericlist = []):
   numericlist.append(nums + 1)
   print(numericlist) 
    
# function calls
fcn(66)
fcn(68)
fcn(70)

執行上述程式碼後,將產生以下輸出 -

[67]
[67, 69]
[67, 69, 71]
廣告