简体   繁体   English

在python中使用def有多个参数

[英]Having more than one parameter with def in python

So in java you can do something like this if you don't know how many parameters you are going to get 所以在java中你可以做这样的事情,如果你不知道你将获得多少参数

private void testMethod(String... testStringArray){

}

How can I do something like this in python 我怎么能在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 . 如果是这样,看看*args**kwargs

See this Basic Guide and How to use *args and **kwargs in Python 请参阅本基本指南以及如何在Python中使用* args和** kwargs

Two short examples from [1] : [1]中的两个简短例子:

Using *args : 使用*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): 并使用**kwargs (关键字参数):

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? 引用这个问题* args和** kwargs是什么意思? :

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. 将* args和/或** kwargs作为函数定义的参数列表中的最后一项,允许该函数接受任意数量的匿名和/或关键字参数。

Sounds like you want: 听起来像你想要的:

def func(*args):
      # args is a list of all arguments

This like a lot of other such information is covered in the Python tutorial , which you should read. 与Python教程中介绍的许多其他类似信息一样,您应该阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM