如何将选定的参数传递给python constru

2024-10-16 20:39:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个初始值设定项:

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

问题

如何构造这个初始值设定项,以便传递选择性参数。你知道吗


Tags: selfnonefalseonlyifparameterfoomyclass
1条回答
网友
1楼 · 发布于 2024-10-16 20:39:36

如果您愿意将示例改为使用等号而不是冒号,那么__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

相关问题 更多 >