關於Python中的引數定義及可變引數
阿新 • • 發佈:2018-12-31
在學習Python過程中,閱讀程式碼中,經常會遇到def f(x)或def f(**x)的函式,為了瞭解其定義,以下對其解釋:
First, 函式的定義:
def function():
pass
這是沒有引數的函式,本函式啥也不幹。
Second,帶引數的函式:
def function(a,b):
print(a)
print(b)
這是帶引數的函式,直接輸出傳入的引數。(注意:這類形式,引數的順序及個數一定要與定義一致,否則會報錯。)
Third, 可變引數的函式:
def function (*x):
print(x)
eg:
function(1, 2, 3, 4)
(1, 2, 3, 4)
這是可變引數的函式,可以傳遞多個引數,且不會報錯。(注:傳遞的引數是以tuple形式儲存。)
Final, 兩個*的函式:
def person(name, age, **other):
print (name, age, 'other: ' + other)
eg:
person(‘mikoy’, 22, city = ‘GuangZhou’)
mikoy 22 {‘city’ : ‘GuangZhou’}
其實傳遞的是一個dict(key,value)