我有一个这样的初始化器:
def __init__(self, options=None, rinse=True, algorithm="foo"):
if options is not None:
self.options = options
else:
self.create_default()
if (rinse==False): #would mean rinse parameter was passed
self.options.rinse = rinse
if (algorithm!="foo"): #would mean algorithm parameter was passed
self.options.algorithm = algorithm
我希望能够通过多种方式调用上述内容。以下是一些例子:
a = MyClass() #nothing was passed
a = MyClass(rinse: False) #only rinse parameter was passed
a = MyClass(algorithm: "bar") #only algorithm parameter was passed
a = MyClass(options, rinse, algorithm) #pass all three arguments
问题
如何构建此初始化程序,以便我可以传递选择性参数。
答案 0 :(得分:1)
如果您愿意更改示例以使用等号而不是冒号,那么__init__
应该可以正常工作:
a = MyClass() #nothing was passed
a = MyClass(rinse= False) #only rinse parameter was passed
a = MyClass(algorithm= "bar") #only algorithm parameter was passed
a = MyClass(options, rinse, algorithm) #pass all three arguments