Python中的引數

2021-09-08 18:18:48 字數 2729 閱讀 7402

* test(arg1,arg2,`*args`)

* test(arg1,arg2,`*args`,`**kwargs`)

*args變長的佔位引數列表 -

**kwargs變長的鍵值對引數列表 -

test(arg1,arg2)引數括弧中列出的識別符號就是佔位引數

*args變長佔位引數是用來傳送乙個非鍵值對的可變數量的引數列表給乙個函式, 可以遍歷得到它

def test_var_args(f_arg, *ar**):

print(type(ar**))

# print("first normal arg:", f_arg)

for arg in ar**:

print("another arg through *ar**:", arg)

test_var_args('yasoob', 'python', 'eggs', 'test')

**kwargs允許你將變長度的鍵值對, 作為引數傳遞給乙個函式, 說白了就是函式的引數是個dict,但是不能直接傳個dict給函式,得加上前導**解包

def test_kwarg(**kwargs):

print(type(kwargs))

# for key, value in kwargs.items():

print(" == ".format(key, value))

test_kwarg(name="foo")

test_kwarg(name="foo", age=26)

test_kwarg(**)

def test_kwarg(name, age, *args, **kwargs):

print('--------------------------------------')

print('all positional args:')

print('name:'.format(name))

print('age:'.format(age))

print('\n')

print('all optional positional *args:')

for arg in args:

print('args:'.format(arg))

print('\n')

print('all keywords **kwargs:')

for key, value in kwargs.items():

print(" == ".format(key, value))

# 只有佔位引數

test_kwarg("foo", 26)

# 佔位引數 + 可選佔位引數

test_kwarg("foo", 26, 'opt1')

# 佔位引數 + 鍵值對引數

test_kwarg("foo", 26, kw1=100, kw2=200)

# 佔位引數 + 可選佔位引數 + 鍵值對引數

test_kwarg("foo", 26, 'opt1', 'opt2', kw1=100, kw2=200)

# --------------------------------------

# all positional args:

# name:

# foo

# age:

# 26

# all optional positional * args:

# all keywords ** kwargs:

# --------------------------------------

# all positional args:

# name:

# foo

# age:

# 26

# all optional positional * args:

# args:

# opt1

# all keywords ** kwargs:

# --------------------------------------

# all positional args:

# name:

# foo

# age:

# 26

# all optional positional * args:

# all keywords ** kwargs:

# kw1 == 100

# kw2 == 200

# --------------------------------------

# all positional args:

# name:

# foo

# age:

# 26

# all optional positional * args:

# args:

# opt1

# args:

# opt2

# all keywords ** kwargs:

# kw1 == 100

# kw2 == 200

python中引數 Python中的引數

python中的引數 1.python函式引數有多重形式 test arg1,arg2,args test arg1,arg2,args kwargs 2.其中比較糊弄人的是 args和 kwargs args 變長的佔位引數列表 kwargs 變長的鍵值對引數列表 3.什麼是佔位引數 test a...

python中的引數 python中的引數

一 位置引數 def test x,y print x print y test 1,2 與形參一一對應 結果如下 二 關鍵字引數 def test1 x,y print x print y test1 y 2,x 3 與形參順序無關 結果如下 三 預設引數 def student name,age...

python中的引數傳遞 python中的引數傳遞

begin 前面在介紹python的六大資料型別的時候提到根據資料可變和不可變進行的資料型別分類 python3 的六個標準資料型別中 不可變資料 3 個 number 數字 string 字串 tuple 元組 可變資料 3 個 list 列表 dictionary 字典 set 集合 pytho...