简体   繁体   English

如何使用可选参数调用python函数

[英]How to call python function with optional parameters

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? 是否可以只分配一个可选参数和一些*参数? eg 例如

create('some name', opt4=True, 1, 2, 3) # I need 1, 2, 3 to be assigned to *parameters

Most 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 . 大多数时候,我不需要更改opt1 ... opt6的值,我只需要更改其中一个,并分配一些其他*parameters So I am looking for a way to avoid setting opt1...opt6 if I don't want to change their default value. 所以我正在寻找一种避免设置opt1 ... opt6的方法,如果我不想更改它们的默认值。

Well for sure this is not nice, but you can probably work on variants of this 确定这不是很好,但你可能可以使用它的变种

def create(name, page=5, opt1=False, opt2=False,
           opt3=False,
           opt4=False,
           opt5=False,
           opt6=False,
           *parameters):
    print(parameters)
    print(page)
    print(opt4)

myArgs = dict(zip(['page','opt1','opt2','opt3','opt4','opt5','opt6'],create.func_defaults))

myArgs['opt4']=True
create("MyName",**myArgs)

In Python 3.x, Try putting parameters before any of the default arguments, example - 在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

Please 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 - 对于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

Again, only way to set the values for opt1...opt6 or page , etc would be using named arguments. 同样,只有设置opt1...opt6page等的值的方法是使用命名参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM