Python関数の任意の数のパラメータを定義します
996 ワード
Pythonでオプションパラメータを定義できることを知っているかもしれません.しかし、関数の任意の数のパラメータを定義する方法もあります.
まず、以下に、オプションパラメータのみを定義する例を示します.
def function(arg1="",arg2=""):
function(“Hello”, “World”)
prints args1: Hello
prints args2: World
function()
prints args1:
prints args2:
次に、任意のパラメータを受け入れる関数をどのように定義するかを見てみましょう.私たちはメタグループを利用して実現します.
def foo(args): # just use ""to collect all remaining arguments into a tuple
foo()
Number of arguments: 0
foo(“hello”)
Number of arguments: 1
Argument 0 is: hello
foo(“hello”,“World”,“Again”)
Number of arguments: 3
Argument 0 is: hello
Argument 1 is: World
Argument 2 is: Again
まず、以下に、オプションパラメータのみを定義する例を示します.
def function(arg1="",arg2=""):
print "arg1: {0}".format(arg1)
print "arg2: {0}".format(arg2)
function(“Hello”, “World”)
prints args1: Hello
prints args2: World
function()
prints args1:
prints args2:
次に、任意のパラメータを受け入れる関数をどのように定義するかを見てみましょう.私たちはメタグループを利用して実現します.
def foo(args): # just use ""to collect all remaining arguments into a tuple
numargs = len(args)
print "Number of arguments: {0}".format(numargs)
for i, x in enumerate(args):
print "Argument {0} is: {1}".format(i,x)
foo()
Number of arguments: 0
foo(“hello”)
Number of arguments: 1
Argument 0 is: hello
foo(“hello”,“World”,“Again”)
Number of arguments: 3
Argument 0 is: hello
Argument 1 is: World
Argument 2 is: Again