简体   繁体   English

python:可选 arguments

[英]python: optional arguments

I would like to obtain a function that works like this:我想获得一个像这样工作的 function:

operations(a, b) = a + b
operations(a, b, operation = 'subtraction') = a - b
operations(a, b, operation = 'multiplication') = a * b
operations(a, b, operation = 'division') = a / b

Operation should be an optional argument that specifies the operation to be performed. Operation 应该是一个可选参数,指定要执行的操作。 By default, it should consider the addition operation.默认情况下,应该考虑加法运算。

I was not able to achieve this using *args and **kwargs, probably because I didn't actually get how they work.我无法使用 *args 和 **kwargs 来实现这一点,可能是因为我实际上并没有了解它们是如何工作的。

Thank you谢谢

Edit: Sorry I was making a stupid mistake.编辑:对不起,我犯了一个愚蠢的错误。 Thanks anyway.不管怎么说,还是要谢谢你。

You just need to provide a default value for the parameter.您只需要为参数提供一个默认值。

def operations(a, b, operation='addition'):
    ...

*args lets you collect arbitrary positional arguments in a single tuple named args . *args允许您在名为args的单个元组中收集任意位置的 arguments 。

def foo(*args):
    print(args)

>>> foo(1, 2)
(1, 2)

**kwargs works the same, but for keyword arguments, collecting them in a dict : **kwargs的工作原理相同,但对于关键字 arguments,将它们收集在dict中:

def foo(**kwargs):
    print(kwargs)

>>> foo(a=1, b=2)
{'a': 1, 'b': 2}

**kwargs is typically used when you just need to pass an unknown set of arguments on to another function call. **kwargs通常在您只需要将一组未知的 arguments 传递给另一个 function 调用时使用。 In your case here, you know that an argument named operation is to be used, so you can specify it by name in the parameter list.在您的情况下,您知道要使用名为operation的参数,因此您可以在参数列表中按名称指定它。


You can also require that it be passed as a keyword argument, like so:您还可以要求将其作为关键字参数传递,如下所示:

def operations(a, b, *, operation='addition'):
    ...

Now operations(a, b, 'subtraction') is illegal;现在operations(a, b, 'subtraction')是非法的; it must be called like operations(a, b) or operations(a, b, operation='subtraction') .它必须像operations(a, b)operations(a, b, operation='subtraction')一样调用。

you can use optional arguments:您可以使用可选的 arguments:

def operation(a, b, tp = "addition"):
    if tp == "subtraction":
        return a - b
    if tp == "division":
        return a / b
    if tp == "multiplication":
        return a * b
    return a + b

print(operation(10, 20) == 30)
print(operation(10, 20, "subtraction") == -10)

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

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