Python正課32 函式引數的補充

2022-01-30 05:17:37 字數 1068 閱讀 4689

def func(x,y,*,a,b):    # 其中,a和b稱之為命名關鍵字引數

print(x,y)

print(a,b)

func(1,2,b=222,a=111)

func() # typeerror: func() missing 2 required positional arguments: 'x' and 'y'

# 示例

def func(x,y,*,a=11111,b): # 不會出現語法錯誤,*後的a和b是命名關鍵字,a=111只是為命名關鍵字形參設定預設值

print(x,y)

print(a,b)

func(1,2,b=22222)

def func(x,y=1,*args,z,**kwargs):

print(x)

print(y)

print(args)

print(z)

print(kwargs)

def func(x,y,z,a,b,c):

print(x,y,z,a,b,c)

func(111,y=222,*[333,444],**)

# 相當於:func(111,y=222,333,444,b=555,c=666)

報錯:typeerror: func() got multiple values for argument 'y' 給y賦了多個值

正確順序應該是:

def func(x,y,z,a,b,c):

print(x,y,z,a,b,c)

func(111,*[222,333],a=444,**)

# 相當於:func(111,222,333,a=444,b=555,c=666)

# 也可以是:

# func(111,*[222,333],**,a=444,)

# 相當於:func(111,3333,4444,b=555,c=666,a=444)

輸出:111 222 333 444 555 666

Python正課36 閉包函式

def f1 x 33333333333333333333 def f2 print x f2 x 11111 def bar x 444444 f1 def foo x 2222 bar foo 輸出 33333333333333333333 思路 呼叫的是函式foo 函式foo 內的x 2222...

python引數函式 Python函式引數總結

coding utf 8 整理一下python函式的各種引數型別 位置引數 呼叫函式時,傳入的兩個值按照位置順序依次賦給引數 def power x,n s 1 while n 0 n n 1 s s x return s print power 5,2 預設引數 簡化函式的呼叫 def power...

python 引數 Python函式 引數

python中將函式作為引數,區分將引數直接寫成函式名和函式名 的區別。def fun1 fun print print print fun 執行fun1 fun4 時,fun為函式fun3的返回值x print type fun type fun type fun fun 執行fun1 fun4 ...