關鍵字引數和預設值引數

2021-10-04 22:07:46 字數 1873 閱讀 7499

#可變引數+關鍵字引數

#關鍵字引數:key=value

defadd

(a,b=10)

:#預設值引數

result=a+b

print

(result)

add(5)

add(4,

7)#a=4,b=7 #此時7會覆蓋b原來的預設值

defadd

(a,b=

7,c=5)

: result=a+b+c

print

(result)

add(1)

#給c賦值而不是給b賦值

add(

1,c=3)

#如果想將6賦值給c,則需要結合關鍵字的key使用

#函式:計算每位同學的年齡和姓名

students=

defprint_boy

(name,

**persons)

:#persons=students

print

('{}喜歡的小鮮肉是:'

.format

(name))if

isinstance

(persons,

dict):

values=persons.values(

)print

(values)

for name,age in values:

print

('{}的年齡是{}'

.format

(name,age)

)print_boy(

'蕊蕊'

,**students)

deffunc

(**kwargs)

:#key word arguments

print

(kwargs)

func(a=

1,b=

3,c=5)

#關鍵字引數

func(

)func(a=1)

dict1=

func(

**dict1)

'''使用函式的時候:

def aa(**kwargs):

print(kwargs)

aa(a=1,b=2,c=3) #將關鍵字裝包成字典

#如果在開發的時候,已知乙個字典

dict1=

aa(**dict1) #a=1,b='hello',c='tom' 拆包的過程

死記:只要在定義函式的時候放星星就是裝包。呼叫的時候就是拆包

'''def

bb(a,b,

*c,**d)

:print

(a,b,c,d)

bb(1,2

)bb(1,

2,3,

4)bb(1,2

,x=10

,y=20

)#因為這裡面含有關鍵字

bb(1,2

,3,x=100

)

執行結果:

15

1113

11蕊蕊喜歡的小鮮肉是:

dict_values([(

'蔡徐坤',20

),('王源',19

),('王俊凱',21

),('易烊千璽',19

)])蔡徐坤的年齡是20

王源的年齡是19

王俊凱的年齡是21

易烊千璽的年齡是1912

python預設值 關鍵字引數

給引數設定預設值非常有用。def passion name,location 中國 return name location s a23foiwe9owef0wfia2 ret1 passion thinking ret2 passion thinking 上海 浦東 print ret1 s re...

方法引數 預設值 引數的預設值陷阱!

今日分享 引數的預設值陷阱 下面定義的函式f,其引數d是乙個預設引數,且為字典型別 def f a,d print f a print f d do some process return d 最後返回字典d,下面呼叫函式f ret dict f 1 第二個引數d使用預設值 ret dict b 2...

python函式之 預設值引數總結

1.預設值引數後的所有引數都必須是預設值引數,直到遇到任意引數列表def f1 a 2 b 3,c或 c 預設值引數後的引數必須都是預設值引數,直到遇到 即可變引數 print a,b,c f1 4,6 輸出 3 4 或3 4 2.預設值引數,傳遞新引數會覆蓋該函式本地符號表中的值,不傳遞則使用預設...