在python中使用def有多个参数 [英] Having more than one parameter with def in python

查看:943
本文介绍了在python中使用def有多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在java中你可以做这样的事情,如果你不知道你会得到多少参数

  private void testMethod(String ... testStringArray){

}

我可以在python中做这样的事情吗?



因为我不能这样做吗?

  def testMethod(... listA):


解决方案

你在说变长参数列表吗?如果是这样,看看 * args ** kwargs



请参阅此基本指南和< a href =http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/ =nofollow noreferrer>如何使用* args和** Python中的kwargs



[1]

使用

  def test_var_args(farg,* args):
打印正式arg:,参数arg中的远程

打印另一个arg:,arg

test_var_args(1,two,3)

结果:

 正式arg:1 
另一个arg:两个
另一个arg:3

并使用 ** kwargs (关键字参数):

  def test_var_kwargs(farg,** kwargs):
打印formal arg:,farg
for kwargs :
printanother keyword arg:%s:%s%(key,kwargs [key])

test_var_kwargs(farg = 1,myarg2 =two,myarg3 = 3)

结果:

  formal arg:1 
another keyword arg:myarg2:two
another keyword arg:myarg3:3

从这个SO问题引用什么是* args和** kwargs是什么意思? b
$ b


将* args和/或** kwargs作为函数的最后一项
定义的参数列表允许该函数接受一个任意的
的匿名和/或关键字参数。



So in java you can do something like this if you don't know how many parameters you are going to get

private void testMethod(String... testStringArray){

}

How can I do something like this in python

as I can't do something like this right?

def testMethod(...listA):

解决方案

Are you talking about variable length argument lists? If so, take a look at *args, **kwargs.

See this Basic Guide and How to use *args and **kwargs in Python

Two short examples from [1]:

Using *args:

def test_var_args(farg, *args):
    print "formal arg:", farg
    for arg in args:
        print "another arg:", arg

test_var_args(1, "two", 3)

Results:

formal arg: 1
another arg: two
another arg: 3

and using **kwargs (keyword arguments):

def test_var_kwargs(farg, **kwargs):
    print "formal arg:", farg
    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

test_var_kwargs(farg=1, myarg2="two", myarg3=3)

Results:

formal arg: 1
another keyword arg: myarg2: two
another keyword arg: myarg3: 3

Quoting from this SO question What do *args and **kwargs mean?:

Putting *args and/or **kwargs as the last items in your function definition’s argument list allows that function to accept an arbitrary number of anonymous and/or keyword arguments.

这篇关于在python中使用def有多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆