python 中函式的引數分為四種:位置引數、預設引數、可變引數、關鍵字引數、命名關鍵字引數
顧名思義,與變數位置有關的引數,例
def
power
(x):
return x**x
即在函式定義時給出引數的值,例
def
power
(x, y=1)
:return x*y
注:預設引數必須指向不變物件
即傳入的是乙個list或者tuple,例
def
calc
(*numbers)
:# numble為乙個list或者tuple,也可以為空
sum=
0for n in numbers:
sum=
sum+ n * n
return
sum
即傳入的是乙個字典,例
def
person
(name, age,
**kw)
:print
('name:'
, name,
'age:'
, age,
'other:'
, kw)
person(
'bob',35
, city=
'beijing'
)# 輸出name: bob age: 35 other:
注:關鍵字引數可以為空
def
f1(a, b, c=0,
*args,
**kw)
:print
('a ='
, a,
'b ='
, b,
'c ='
, c,
'args ='
, args,
'kw ='
, kw)
注:不要同時使用太多的組合,否則函式介面的可理解性很差
python中函式可以返回多個值,例
x,y = move(a, b, c)
實則返回的是乙個tuple Python函式引數中的 ,
問題 python的函式定義中有兩種特殊的情況,即出現 的形式。如 def execute command self,args,options 等。解釋 用來傳遞任意個無名字引數,這些引數會乙個tuple的形式訪問。用來處理傳遞任意個有名字的引數,這些引數用dict來訪問。應用 的應用 def fu...
Python中的函式引數
python中的引數由於沒有特定的指示方式,所以傳遞引數時也可將其他函式作為引數傳入。傳遞格式 def fun name x,y,z 其中x,y,z都可作為其他函式的名稱 示例 def fun x,y,f return f x f y print fun 10,34,abs 結果 2.1 map函式...
Python中函式的引數
位置引數,是函式中最常用的引數。必選引數就是在呼叫函式的時候必須指定引數值。例如 定義加法函式plus,引數a,b就是必選引數 def plus a,b c a b return c 呼叫函式plus時,必須給引數a,b傳遞值 d plus 1,2 輸出結果d print d 預設引數是指給函式引數...