python函数形参星号

形参前面加一个星号,传入的参数转换成元组

def print_everything(*args):
    for count, thing in enumerate(args):
        print('{0}.{1}'.format(count,thing))
print_everything('apple','banana','cabbage')#参数传入元组

0.apple
1.banana
2.cabbage

遍历enumerate时,count表示序号,thing表示内容。


def print_everything2(*args):
    for thing in iter(args):
        print('{0}'.format(thing))
print_everything2('apple','banana','cabbage')#参数传入元组

apple
banana
cabbage


def print_everything3(*args):
    print(args)
    x=iter(args[0])
    while True:
        try:
            print( next(x))
        except StopIteration:
            break

print_everything3(['apple','banana','cabbage'])#参数传入元组

([‘apple’, ‘banana’, ‘cabbage’],)
apple
banana
cabbage

x=iter(元组/列表)
使用next(x)输出

while True:
    try:
        print(next(x))
    except Exception:
        break

def print_everything4(*args):
    print(args)
    print(*args)
    x=iter(args)
    while True:
        try:
            print( next(x))
        except StopIteration:
            break

print_everything4('apple','banana','cabbage')#参数传入元组

(‘apple’, ‘banana’, ‘cabbage’)
apple banana cabbage
apple
banana
cabbage

形参前面加两个星号,形参为字典

调用该函数时将apple = ‘fruit’,cabbage = ‘vegetable’转化为一个字典。

def table_things(**kwargs):
    for name, value in kwargs.items(): #字典
        print('{0} = {1}'.format(name, value))

table_things(apple = 'fruit',cabbage = 'vegetable')

cabbage = vegetable
apple = fruit


def table_things2(**kwargs):
    print(kwargs)
    for name, value in kwargs.items(): #字典
        print('{0} = {1}'.format(name, value))

table_things2(apple = 'fruit',cabbage = 'vegetable')

{‘cabbage’: ‘vegetable’, ‘apple’: ‘fruit’}
cabbage = vegetable
apple = fruit


def fun(key=236):
    print(key)


def table_things3(**kwargs):
    print(kwargs)
    fun(**kwargs)
    for name, value in kwargs.items(): #字典
        print('{0} = {1}'.format(name, value))

table_things3(key=234)

{‘key’: 234}
234
key = 234

前面加两个星号的形参,可继续传入另一个函数f,填充f的部分形参值。必须满足f的参数名包含字典的key。

def fun(qwe=23,key=236,apg=111):
    print(qwe)
    print(key)
    print(apg)


def table_things3(**kwargs):
    print(kwargs)
    fun(**kwargs)
    for name, value in kwargs.items(): #字典
        print('{0} = {1}'.format(name, value))

table_things3(key=234)

{‘key’: 234}
23
234
111
key = 234


作为函数形参时,加上**的参数应该放在最后,放在普通参数前面
貌似编译会出问题。例如

def fun(opt,**arg)
def fun(opt=2,**arg)  #wrong

这样是不可取的

def fun(**arg,opt)  #wrong
def fun(**arg,opt=2)  #wrong

作为函数形参时,加上**的参数**dic,表示在调用函数时,将若干形如key=value的式子收集起来组成字典。

def fun(**dic):
    pass

fun(a=2,c=2,d=3)

作为调用函数的实际参数时,**dic表示将一个字典拆成若干个key-value对,赋值给形参。与**dic一起写的参数必须是key=value形式,否则运行不了。

def fun2(a=4,c=4,d=4):
    print('a=',a)
    print('c=',c)
    print('d=',d)

dic={ 'a':2,'d':3  }
c=3
fun2(**dic,c=c) #如果写成fun2(**dic,c)出错


#a= 2
#c= 3
#d= 3


def fun2(a=4,c=4,d=4):
    print('a=',a)
    print('c=',c)
    print('d=',d)

dic={ 'a':2,'d':3  }
c=3
fun2(c=c,**dic)

#a= 2
#c= 3
#d= 3
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页