python中函数的收集参数

 

1、

复制代码
>>> def a(*xxx):
    print("total length is %d" % len(xxx))
    print("the second element is :",xxx[1])

    
>>> a("aaa","bbb","ccc","ddd","eee","fff")
total length is 6
the second element is : bbb
复制代码

 

复制代码
>>> def a(*xxx,m):
    print("collection parameter is:",xxx)
    print("keyword parameter is :",m)

    
>>> a(1,2,3,4,5)
Traceback (most recent call last):
  File "<pyshell#616>", line 1, in <module>
    a(1,2,3,4,5)
TypeError: a() missing 1 required keyword-only argument: 'm'
>>> a(1,2,3,4,m = 5)      ## 收集参数之外的参数使用关键字参数
collection parameter is: (1, 2, 3, 4)
keyword parameter is : 5
复制代码
复制代码
>>> def a(*xxx,m = 5):         ## 收集参数之外的参数使用默认参数
    print("collection parameter is :",xxx)
    print("keyword parameter is :", m)

    
>>> a(1,2,3,4,5,6)
collection parameter is : (1, 2, 3, 4, 5, 6)
keyword parameter is : 5
复制代码

 

2、

复制代码
>>> def a(*xxx):   ## 单星号收集参数打包为元组
    print(type(xxx))

    
>>> a(111,222,333,444)   
<class 'tuple'>
>>> def b(**xxx):   ## 双型号收集参数打包为字典
    print(type(xxx))

    
>>> b(a = "1111",b = "2222",c = "3333")
<class 'dict'>
复制代码

 

posted @   小鲨鱼2018  阅读(107)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示