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

时间:2018-05-17 17:54:37

标签: python python-3.x class

我想知道如果我想将可选参数传递给函数,python中是否有任何好的做法如何处理案例。

我在课堂上有这个功能:

[['10', '20', 2], ['10', '21', 2], ['10', '1', 2], ['10', '0', 3], ['10', '3', 2],
 ['10', '2', 2], ['10', '5', 3], ['10', '4', 3], ['10', '7', 2], ['10', '6', 2],
 ['10', '9', 2], ['10', '8', 2], ['10', '11', 2], ['10', '10', 2], ['10', '13', 2],
 ['10', '12', 2], ['10', '15', 2], ['10', '14', 2], ['10', '17', 0], ['10', '16', 3],
 ['10', '19', 2], ['10', '18', 2], ['1', '20', 3], ['1', '21', 3], ['1', '1', 3],
 ['1', '0', 0], ['1', '3', 3], ['1', '2', 3], ['1', '5', 4], ['1', '4', 4],
 ['1', '7', 3], ['1', '6', 3], ['1', '9', 3], ['1', '8', 3], ['1', '11', 3],
 ['1', '10', 3], ['1', '13', 3], ['1', '12', 3], ['1', '15', 3]]

我现在可以做的就是用if来处理,但我不认为这是最好的方法。

1 个答案:

答案 0 :(得分:3)

如果要将可选参数传递给函数,请考虑使用*args**kwargs,或者只使用默认参数。

例如*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