[python][oldboy] * **的用法
* 和**主要用在函数的参数中,
1 # coding=utf8 2 3 """ 4 三种编码: 5 1 python程序代码的编码 6 # coding=utf8 7 2 设置/查看python程序运行环境的编码 8 import sys 9 查看 10 sys.getdefaultencoding() 11 设置 12 reload(sys) 13 sys.setdefaultencoding('utf-8') 14 3 python程序读取外部文件,网页内容的编码 15 encode,decode 16 """ 17 18 def function(*args, **kwargs): 19 """ 20 :param args: 表示任何多个无名参数,这些参数会以一个tupe的形式访问 21 :param kwargs: 用来处理任意个有名字的参数,这些参数用dict来访问 22 :return: 23 """ 24 print "args type = %s" % type(args) 25 print "args = %s" % str(args) 26 for i, item in enumerate(args): 27 print "args[%d] = %s" % (i, item) 28 29 print "------------" 30 print "kwargs type = %s" % type(kwargs) 31 print "kwargs = %s" % kwargs 32 for k, v in kwargs.items(): 33 print "%s:%s" % (k, v) 34 35 36 function(1, 2, 3, name="liuzhipeng", sex="male")
结果为
C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/oldboy/lesson_3/44.py args type = <type 'tuple'> args = (1, 2, 3) args[0] = 1 args[1] = 2 args[2] = 3 ------------ kwargs type = <type 'dict'> kwargs = {'name': 'liuzhipeng', 'sex': 'male'} name:liuzhipeng sex:male Process finished with exit code 0
* 和** 在打印元组(列表)和字典的时候很有用
print "i am {name}, and age is {age}".format(**{"name": "lzp", "age": 14}) print "i am {}, and age is {}".format(*("lzp",14))
i am lzp, and age is 14 i am lzp, and age is 14