简体   繁体   English

具有** kwargs的功能

[英]Functions with **kwargs

I want to write a Python function myfun that accepts only optional parameters, a and b . 我想编写一个仅接受可选参数ab的Python函数myfun

If either one of a or b is not specified when calling myfun , how can I tell myfun to use some default value for a and b ? 如果在调用myfun时未指定ab之一,如何告诉myfunab使用一些默认值?

def myfun(**kwargs):

    a = kwargs.get('a', None)
    # if a is not specified, use default a=4.4

    b = kwargs.get('b', None)
    # if b is not specified, use default b=2.1    

    c = 2*a
    d = 3.1*b

    return c, d


c,d = myfun(a=1,b=2)
print c,d

**kwargs is used to collect an arbitrary number of keyword arguments. **kwargs用于收集任意数量的关键字参数。 If you only want to accept two, then it is not the right tool to be using. 如果您只想接受两个,则它不是使用的正确工具。

Instead, you should specify default values for the a and b parameters: 相反,您应该为ab参数指定默认值:

def myfun(a=4.4, b=2.1):

Demo: 演示:

>>> def myfun(a=4.4, b=2.1):
...     print('a={}\nb={}'.format(a, b))
...
>>> myfun()
a=4.4
b=2.1
>>> myfun(a=1)
a=1
b=2.1
>>> myfun(a=1, b=2)
a=1
b=2
>>> myfun(b=2)
a=4.4
b=2
>>>

set them to a default value: 将它们设置为默认值:

def myfun(a=4.4,b=2.1):

There would be no way for a user to know they could set a and b if you did not add them as keywords in the function definition. 如果您没有在功能定义中将它们添加为关键字,那么用户将无法知道他们可以设置ab

If you were setting a value using kwargs.get you would pass the default value to get: 如果使用kwargs.get设置值,则将传递默认值以获取:

a = kwargs.get('a', 4.4) # a = 4.4 if a not in kwargs

b = kwargs.get('b', 2.1)

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

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