简体   繁体   English

在以下python代码场景中使用kwargs是否正确?

[英]Is it correct to use kwargs in the following scenario of python code?

Is it correct to use kargs in the following scenario?在以下场景中使用 kargs 是否正确?

I have a function that needs five parameters in the call with two of them optional.我有一个函数在调用中需要五个参数,其中两个是可选的。 So, I can delete it as:所以,我可以将其删除为:

def f(p1, p2, p3, p4, p5, o1=None, o2=None)

or或者

def f(**kwargs)

Because I'm doing things like this with the params:因为我正在用参数做这样的事情:

orig_path = "{0}/{1}/{3}/{4}".format(p1, p2, p3, p4)

or或者

orig_path = "{p1}/{p2}/{p3}/{p4}".format(kwargs)

I don't know which style is the correct way in Python to use in the declarations.我不知道哪种样式是 Python 中在声明中使用的正确方式。 Is there any guide to look for the correct use of kwargs?.是否有任何指南可以寻找正确使用 kwargs 的方法? I've seen in the Amazon boto3 api usually uses the kwargs construction but...我在亚马逊 boto3 api 中看到通常使用 kwargs 结构,但是......

As a rule of thumb, you should always write out all parameters in a function definition, if you can, and ideally give them descriptive names.根据经验,如果可以,您应该始终在函数定义中写出所有参数,并且最好为它们提供描述性名称。

The Zen of Python says Python

Explicit is better than implicit.显式优于隐式。

and also并且

Readability counts.可读性很重要。

Making the parameters explicit helps you prevent many mistakes, like calling the function with too many or too few parameters or with keyword parameters that don't exist.使参数显式可帮助您避免许多错误,例如使用过多或过少的参数或不存在的关键字参数调用函数。

It also helps readability a lot, as you can easily spot from the definition how many and which parameters the function expects and in which order and what the defaults for possible keyword parameters are.它还有助于提高可读性,因为您可以从定义中轻松发现函数期望的参数数量和参数以及可能的关键字参数的顺序和默认值。 Sometimes, you can even guess what the function does via good parameter names without having to look at the documentation.有时,您甚至可以通过良好的参数名称猜测函数的作用,而无需查看文档。

Some IDEs can even look up the definition automatically when you write a call and alert you to possible problems while you're typing.某些 IDE 甚至可以在您编写调用时自动查找定义,并在您键入时提醒您可能出现的问题。

Do this:做这个:

def twiddle_knobs(tuning, volume, panning=None, bass=6.0, midrange=-2.0, treble=1.5):
    """Modify the most important radio controls."""

    my_radio.modify_control(radio.TUNEFREQ, value=max(min(tuning, 120.0), 85.0))
    my_radio.modify_control(radio.VOL_MASTER, value=(volume / 100.0))

    if panning is not None:
        my_radio.modify_control(radio.VOL_LEFT, value=min(1.0 - panning / 100.0, 1.0))
        my_radio.modify_control(radio.VOL_RIGHT, value=min(1.0 + panning / 100.0, 1.0))

    for control, value in ((radio.EQU_BASS, bass),
                           (radio.EQU_MID,  midrange),
                           (radio.EQU_TREB, treble)):

        my_radio.modify_control(control, value=value, unit=radio.DB)

Do not do this:不要这样做:

 def twiddle_knobs(*args, **kwargs): # WARNING: never do this! my_radio.modify_control(radio.TUNEFREQ, max(min(args[0], 120.0), 85.0)) my_radio.modify_control(radio.VOL_MASTER, args[1] / 100.0) if kwargs.get("panning") is not None: my_radio.modify_control(radio.VOL_LEFT, min(1.0 - kwargs["panning"] / 100.0, 1.0)) my_radio.modify_control(radio.VOL_RIGHT, min(1.0 + kwargs["panning"] / 100.0, 1.0)) for control, param, default in ((radio.EQU_BASS, "bass", 6.0), (radio.EQU_MID, "midrange", -2.0), (radio.EQU_TREB, "treble", 1.5)): my_radio.modify_control(control, kwargs.get(param, default), radio.DB)

So when is it OK to use *args and *kwargs ?那么什么时候可以使用*args*kwargs呢?

  • One use for *args is when you need to receive a list of things that are alike and serve the same function . *args一个用途是当您需要接收具有相同功能的相似事物的列表时。 However, you could also just use a normal parameter and have the caller explicitly pass in a list.但是,您也可以只使用普通参数并让调用者显式传入一个列表。 Sometimes, calling the function with func([thing]) can seem awkward, though, particularly when most of the time you pass only one thing or no thing at all.有时,使用func([thing])调用函数可能看起来很尴尬,尤其是当大多数时间你只传递一件事或根本不传递任何东西时。 Those are the times when *args would improve the situation.那些是*args会改善情况的时候。

  • Also, when you need to pass some of the positional and/or keyword arguments your function received on to another function you don't have control over and you don't want to dictate which parameters your caller is allowed to have handed through, then *args and *kwargs - used after your explicit parameters - are the way to achieve that.此外,当您需要将您的函数接收到的某些位置和/或关键字参数传递给另一个您无法控制的函数时,您也不想规定允许调用者传递哪些参数,然后*args*kwargs -在您的显式参数之后使用- 是实现这一目标的方法。

  • If you have a set of keyword parameters that serve a strongly related function and you cannot exactly predefine upfront what the keywords will be , because they might depend upon something that's dynamically changing, that would also be a good reason for using *kwargs .如果您有一组关键字参数提供强相关功能,并且您无法预先准确地预定义关键字是什么,因为它们可能取决于动态变化的内容,这也是使用*kwargs一个很好的理由。

This list is not exhaustive, but it should give you a general idea.此列表并非详尽无遗,但它应该可以让您大致了解。

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

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