我有以下功能:
def create(self, name, page=5, opt1=False, opt2=False, opt3=False, opt4=False, opt5=False, opt6=False, *parameters):是否可以只分配一个可选参数和一些*参数? 例如
create('some name', opt4=True, 1, 2, 3) # I need 1, 2, 3 to be assigned to *parameters大多数时候,我不需要更改opt1 ... opt6的值,我只需要更改其中一个,并分配一些其他*parameters 。 所以我正在寻找一种避免设置opt1 ... opt6的方法,如果我不想改变它们的默认值。
I've got the following function:
def create(self, name, page=5, opt1=False, opt2=False, opt3=False, opt4=False, opt5=False, opt6=False, *parameters):Is it possible to assign only one of the optional parameters, and some *parameters? e.g.
create('some name', opt4=True, 1, 2, 3) # I need 1, 2, 3 to be assigned to *parametersMost of the time, I don't need to change the values of opt1...opt6, I only need to change maybe one of them, and assign some other *parameters. So I am looking for a way to avoid setting opt1...opt6 if I don't want to change their default value.
最满意答案
在Python 3.x中,尝试在任何默认parameters之前放置parameters ,例如 -
def create(self, name , *parameters, page=5, opt1=False, opt2=False,opt3=False, opt4=False,opt5=False, opt6=False): print(parameters) print(page) print(opt4) In [31]: create('C', 'some name', 1, 2, 3, opt4 = True) (1, 2, 3) 5 True请理解,使用此方法,您只能使用命名参数调用具有默认值的参数。
对于Python 2.x,您可以尝试使用*parameters ,然后使用**kwargs作为默认参数 -
>>> def create(self, name, *parameters, **kwargs): ... kwargs.setdefault('opt4',False) #You will need to do for all such parameters. ... print(parameters) ... print(kwargs['opt4']) ... >>> create('C', 'some name', 1, 2, 3, opt4 = True) (1, 2, 3) True同样,只有设置opt1...opt6或page等的值的方法是使用命名参数。
In Python 3.x, Try putting parameters before any of the default arguments, example -
def create(self, name , *parameters, page=5, opt1=False, opt2=False,opt3=False, opt4=False,opt5=False, opt6=False): print(parameters) print(page) print(opt4) In [31]: create('C', 'some name', 1, 2, 3, opt4 = True) (1, 2, 3) 5 TruePlease understand that with this method, you can only call the arguments with default value using named arguments.
For Python 2.x , you can try using *parameters and then **kwargs for the default parameters -
>>> def create(self, name, *parameters, **kwargs): ... kwargs.setdefault('opt4',False) #You will need to do for all such parameters. ... print(parameters) ... print(kwargs['opt4']) ... >>> create('C', 'some name', 1, 2, 3, opt4 = True) (1, 2, 3) TrueAgain, only way to set the values for opt1...opt6 or page , etc would be using named arguments.
更多推荐
发布评论