如何使用可选参数调用python函数(How to call python function with optional parameters)

编程入门 行业动态 更新时间:2024-10-28 04:22:32
如何使用可选参数调用python函数(How to call python function with optional parameters)

我有以下功能:

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 *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. 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 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 -

>>> 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.

更多推荐

本文发布于:2023-04-28 07:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1330931.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   如何使用   函数   参数   optional

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!