Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python必需的变量样式_Python - Fatal编程技术网

Python必需的变量样式

Python必需的变量样式,python,Python,对于需要关键字参数'required_arg'的Python方法,最好的样式是什么: def test_method(required_arg, *args, **kwargs): def test_method(*args, **kwargs): required_arg = kwargs.pop('required_arg') if kwargs: raise ValueError('Unexpected keyword arguments: %s' %

对于需要关键字参数'required_arg'的Python方法,最好的样式是什么:

def test_method(required_arg, *args, **kwargs):


def test_method(*args, **kwargs):
    required_arg = kwargs.pop('required_arg')
    if kwargs:
        raise ValueError('Unexpected keyword arguments: %s' % kwargs)

还是别的什么?我希望将来在我的所有方法中都使用它,因此我正在寻找处理Python方法中所需的关键字参数的最佳实践方法。

目前为止的第一种方法。为什么要复制语言已经为您提供的东西


大多数情况下都应该知道可选参数(只有在无法知道参数时才使用*args和**kwargs)。通过为可选参数提供默认值(
def-bar(foo=0)
def-bar(foo=None)
)来表示可选参数。注意
defbar(foo=[])
的经典用法。

第一种方法为您提供了为所需参数命名的机会;使用*args则不会。需要时使用*args很好,但是为什么要放弃更清楚地表达意图的机会呢?

如果不需要任意的关键字参数,请省去**参数。出于对所有神圣事物的爱,如果你有需要的东西,就让它成为一个正常的论据

与此相反:

def test_method(*args, **kwargs):
    required_arg = kwargs.pop('required_arg')
    if kwargs:
        raise ValueError('Unexpected keyword arguments: %s' % kwargs)
这样做:

def test_method(required_arg, *args):
    pass

第一种方法还允许我在调用函数时使用位置参数。第二个要求我使用命名参数。