Python Parameter with Single or Double Star

single star paramter

方法中的參數帶單個星號,表示要以tuple的方式呼叫方法。

def foo(*args):
    for arg in args:
        print(arg)

foo(1, 'b', 3)

執行結果:

1
b
3

double star paramter

方法中的參數帶兩個星號,表示要以dictionary的方式呼叫方法。

def foo(**dicts):
    for key in dicts:
        print(key, dicts[key])

foo(name='Bob', age=18)

執行結果:

name Bob
age 18

mix

上面提到的兩種帶星號參數,可以與一般參數混合使用,呼叫方法時必須對應參數順序。

def mix(arg, *args, **dicts):
    print('arg:')
    print(arg)

    print('args:')
    for arg in args:
        print(arg)

    print('dicts:')
    for key in dicts:
        print(key, dicts[key])

mix(8, 'a', 'b', 5, name='Bob', age=18)

執行結果:

arg:
8

args:
a
b
5

dicts:
name Bob
age 18

參考資料

https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters

results matching ""

    No results matching ""