Python中类/函数中的可选参数

Python中类/函数中的可选参数,python,python-3.x,class,Python,Python 3.x,Class,我想知道,如果我想将可选参数传递给函数,python中是否有一些很好的实践来处理这些情况 我在课堂上有这个功能: def gen(self, arg1, arg2, optional): if optional exists do that: print(optional) else: print(arg1, arg2) 我现在所能做的就是用IF处理这个问题,但是我认为这不是最好的方法。 < P>如果你想把可选的参数传递给函数,考虑使用 *ARG

我想知道,如果我想将可选参数传递给函数,python中是否有一些很好的实践来处理这些情况

我在课堂上有这个功能:

def gen(self, arg1, arg2, optional):
    if optional exists do that:
        print(optional)
    else:
        print(arg1, arg2)

我现在所能做的就是用IF处理这个问题,但是我认为这不是最好的方法。

< P>如果你想把可选的参数传递给函数,考虑使用<代码> *ARGs<代码>和<代码> *KWARGS < /代码>,或者只使用默认参数.< /P>
def gen(self, arg1, arg2, optional=None):
    if optional:
        # do something
e、 g带有
*args
**kwargs

In [3]: def test(a, b, c, *args, **kwargs):
   ...:     print a, b, b
   ...:     if args:
   ...:         print args # do something, which is optional
   ...:     if kwargs:
   ...:         print kwargs # do something, which is optional
   ...:
   ...:

In [4]: test(1, 2, 3, 4, 5 ,6, 7, name='abc', place='xyz')
1 2 2
(4, 5, 6, 7)
{'place': 'xyz', 'name': 'abc'}

In [5]:
e、 g.使用默认参数

def gen(self, arg1, arg2, optional=None):
    if optional:
        # do something

如果您想将可选参数传递给函数,请考虑使用<代码> *ARGs<代码> >代码> ** kWARGS 或只使用默认参数.< /P>

def gen(self, arg1, arg2, optional=None):
    if optional:
        # do something
e、 g带有
*args
**kwargs

In [3]: def test(a, b, c, *args, **kwargs):
   ...:     print a, b, b
   ...:     if args:
   ...:         print args # do something, which is optional
   ...:     if kwargs:
   ...:         print kwargs # do something, which is optional
   ...:
   ...:

In [4]: test(1, 2, 3, 4, 5 ,6, 7, name='abc', place='xyz')
1 2 2
(4, 5, 6, 7)
{'place': 'xyz', 'name': 'abc'}

In [5]:
e、 g.使用默认参数

def gen(self, arg1, arg2, optional=None):
    if optional:
        # do something

根据您的示例,如果存在
optional
,您是否真的忽略
arg1
arg2
?您可以根据您的示例进行参考,如果存在
optional
,您真的忽略
arg1
arg2
吗?您可以参考