【问题标题】:How do I define an optional argument in function before an un-optional argument?如何在非可选参数之前在函数中定义可选参数?
【发布时间】:2018-05-07 22:10:02
【问题描述】:

我正在研究一维细分类。每个段由 2 个点定义;左边界和右边界。

我希望左边界是可选的(默认为 0)。为此,我将类的init 函数定义为def __init__(self, right, left = 0)。 但是,我希望先给定左参数来定义段; 例如:Seg = Segment(1,5)。 Python 不允许我将函数定义为__init__(self, left = 0, right),那么解决这个问题的最佳解决方案是什么?

【问题讨论】:

标签: python class arguments default


【解决方案1】:
def my_func(*args):
        if len(args) == 0:
                print 'missing mandatory param'
        elif len(args) == 1:
                left = 0
                right = args[0]
        elif len(args) == 2:
                left = args[0]
                right = args[1]
        else:   
                print 'wrong number of params provided'

        print 'left is {}'.format(left)
        print 'right is {}'.format(right)

当提供left和right时,它会将left参数作为left的值

my_func(1,2)
left is 1
right is 2

当只提供 right 时,默认 left 为默认值

my_func(3)
left is 0
right is 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    相关资源
    最近更新 更多