脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python星号*与**用法分析

Python星号*与**用法分析

2021-01-11 00:30毕加索的ma Python

这篇文章主要介绍了Python星号*与**用法,结合实例形式较为详细的分析了Python中的星号*与**在函数参数及数值运算中的相关使用技巧,需要的朋友可以参考下

本文实例分析了Python星号*与**用法。分享给大家供大家参考,具体如下:

1. 加了星号(*)的变量名会存放所有未命名的变量参数,不能存放dict,否则报错。

如:

?
1
2
3
4
5
6
7
def multiple(arg, *args):
  print "arg: ", arg
  #打印不定长参数
  for value in args:
    print "other args:", value
if __name__ == '__main__':
  multiple(1,'a',True)

输出:

Python星号*与**用法分析

2. 加了星号(**)的变量名会存放所有未命名的变量参数

?
1
2
3
4
5
6
def multiple2(**args):
  #打印不定长参数
  for key in args:
    print key + ":" + bytes(args[key])
if __name__ == '__main__':
  multiple2(name='Amy', age=12, single=True)

输出

Python星号*与**用法分析

3. 有 *args 和 **dictargs:

?
1
2
3
4
5
6
7
8
9
10
def multiple(arg, *args, **dictargs):
  print "arg: ", arg
  #打印args
  for value in args:
    print "other args:", value
  #打印dict类型的不定长参数 args
  for key in dictargs:
    print "dictargs:" + key + ":" + bytes(dictargs[key])
if __name__ == '__main__':
  multiple(1,'a',True, name='Amy',age=12, )

输出:

Python星号*与**用法分析

另外,在Python数学运算中*代表乘法,**为指数运算,示例代码如下:

?
1
2
3
4
5
>>> 2*4
8
>>> 2**4
16
>>>

希望本文所述对大家Python程序设计有所帮助。

原文链接:http://www.cnblogs.com/paulwinflo/p/7999398.html

延伸 · 阅读

精彩推荐