编程语言
首页 > 编程语言> > python显式没有传递可选参数

python显式没有传递可选参数

作者:互联网

想象一下以下场景:

class A:
    def __init__(self, arg1=3, arg2=5):
        pass

def createA(arg1=None, arg2=None):
    if arg1 is None:
        if arg2 is None:
            a = A()
        else:
            a = A(arg2=arg2)
    else:
        if arg2 is None:
            a = A(arg1=arg1)
        else:
            a = A(arg1=arg1, arg2=arg2)
    return a

什么是实现此行为的最佳方式,请注意以下事项:

>我不能/不想改变A级
>我不想显式地将A的构造函数参数的默认值添加到createA函数中?

例如,是否有任何值表示未通过可选参数?
就像是:

if arg1 is None:
    newArg1 = NotPassed
else:
    newArg1 = arg1

if arg2 is None:
    newArg2 = NotPassed
else:
    newArg2 = arg2
A(arg1=newArg1, arg2=newArg2)

解决方法:

def create_A(arg1=None, arg2=None):
    kwargs = {}
    if arg1 is not None: kwargs['arg1'] = arg1
    if arg1 is not None: kwargs['arg2'] = arg2
    return A(**kwargs)

或者甚至是

def create_A(**kwargs):
    return A(**kwargs)

标签:python,optional-parameters
来源: https://codeday.me/bug/20190725/1537044.html