Python函式:動態引數
阿新 • • 發佈:2018-12-11
前面jacky說,形式引數有幾個,實際引數是不是就有幾個(預設引數除外,預設引數只能放在最後面)
動態引數1-一個星號變元組
-
動態引數存在的意義?
- 函式的作者有時候也不知道這個函式到底需要多少個引數,這時候動態引數就有存在的意義了
-
動態引數建立-加*
- 底層原理是:把數值型或其他資料型別變成了元組型別,是元組了就可以多加實際引數了
#不用動態引數
def f1(a):
print(a,type(a))
f1(123)
>>> 123 <class'int'>
#使用動態引數
def f1(*a):
print(a,type(a))
f1(123 ,456,789)
>>> (123,456,789) <class'tuple'>
f1(123,[11,22,33],{"key1":"values2"})
>>>(123,[11,22,33],{"k1":"values2"})
動態引數2-兩個星號變字典
def f1(**a):
print(a,type(a))
f1(k1=123,k2=456)
>>>{'k1':123,'k2':456} <class 'dict'>
動態引數的規範書寫
# *args, **kwargs
def f1(*args, **kwargs` )
為動態引數傳入列表、字典、元組
def f1(*args):
print(args,type(args))
li = [11,22,33]
f1(li)
f1(*li) #加*相當於for迴圈遍歷了列表裡的元素
>>>([11,22,33],)<class 'tuple'>
>>>(11,22,33)<class 'tuple'>
def f1(**kwargs):
print(kwargs,type(kwargs))
dic = {"k1":123}
f1(k1=dic)
f1(**dic)
>> >{'k1':{'k1':123}}<class 'dict'>
>>> {'k1':123}<class 'dict'>