想象以下场景:
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)
答案 0 :(得分:8)
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)