【问题标题】:Optional argument in class/function in Python [duplicate]Python中的类/函数中的可选参数[重复]
【发布时间】:2018-10-28 02:14:47
【问题描述】:

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

我在课堂上有这个功能:

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

我现在能做的就是通过 if 来处理它,但我认为这不是最好的方法。

【问题讨论】:

标签: python python-3.x class


【解决方案1】:

如果您想将可选参数传递给函数,请考虑使用*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]:

例如带默认参数。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-01
    • 2023-03-21
    • 2020-12-12
    • 1970-01-01
    • 2020-01-28
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多