*args的用法

*args和**kwargs主要用于函数定义。*args和**kwargs允许您将数量可变的参数传递给函数。变量在这里的意思是,您事先不知道用户可以向您的函数传递多少参数,因此在本例中使用这两个关键字。*args用于向函数发送非关键字可变长度参数列表。下面是一个帮助您了解情况的示例:

选择 | 换行 | 行号
  1. def test_var_args(f_arg, *argv):
  2.     print("first normal arg:", f_arg)
  3.     for arg in argv:
  4.         print("another arg through *argv:", arg)
  5.  
  6. test_var_args('yasoob', 'python', 'eggs', 'test')

这会产生以下结果:

选择 | 换行 | 行号
  1. first normal arg: yasoob
  2. another arg through *argv: python
  3. another arg through *argv: eggs
  4. another arg through *argv: test

标签: python

评论已关闭