3

想象以下场景:

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)
4

1 回答 1

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)
于 2012-10-18T17:16:01.577 回答