Python变量前'*'和'**'的作用


Python的在形参前加'*'和'**'表示动态形参

在形参前加'*'表示可以接受多个实参值存进数组

def F(a, *b)
    print(a)
    print(b)

F(1, 2, 3)

'''
1    
(2, 3)
'''

对于在形参前加'**'表示表示接受参数转化为字典类型

def F(**a)
    print(a)

F(x=1, y=2)

#{'x': 1, 'y': 2}

混合运用

def F(a, *b, **c)
    print(a)
    print(b)
    print(c)

F(1, 2, 3, x=4, y=5)

'''
1
(2, 3)
{'x': 4, 'y': 5}
'''
def F(*a)
    print(a)

ls = [1, 2, 3]
F(ls)  #表示列表作为一个元素传入
F(*ls) #表示列表元素作为多个元素传入

'''
([1, 2, 3],)
(1, 2, 3)
'''
def F(**a)
    print(a)

dt = dict(x=1, y=2)
F(x=1, y=2) 
F(**dt)  #作为字典传入

'''
{'x': 1, 'y':2}
{'x': 1, 'y':2}
函数调用时
dt = dict(color='red', fontproperties='SimHei')
plt.plot(**dt)  
等价于
plt.plot(color='red', fontproperties='SimHei')
'''

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM