Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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_Python 2.7 - Fatal编程技术网

Python 没有默认值的命名参数?

Python 没有默认值的命名参数?,python,python-2.7,Python,Python 2.7,我知道我可以创建一个命名的参数化python函数,比如 def t(a=None, b=None): return a+b 然后我可以打电话给你 t(b=2, a=5) 但是,如果a和b都不是可选的,那么我需要在运行时签入函数,例如 def t(a=None, b=None): if a is not None and b is not None: return a+b else: raise Exception('Missing a

我知道我可以创建一个命名的参数化python函数,比如

def t(a=None, b=None):
    return a+b
然后我可以打电话给你

 t(b=2, a=5)
但是,如果
a
b
都不是可选的,那么我需要在运行时签入函数,例如

def t(a=None, b=None):
    if a is not None and b is not None:
        return a+b
    else:
        raise Exception('Missing a or b')
是否有可能在编译时签入并尽快失败

e、 g

但是,如果a和b都不是可选的,那么我需要在运行时签入函数,例如

def t(a=None, b=None):
    if a is not None and b is not None:
        return a+b
    else:
        raise Exception('Missing a or b')
不,你没有。只是不提供默认值:

def t(a, b):
    return a + b
尝试在没有正确数字参数的情况下调用它:

t()
t(c=4)
将导致错误:

TypeError: t() takes exactly 2 arguments (0 given)
TypeError: t() got an unexpected keyword argument 'c'
或者,尝试使用名称不正确的参数调用它:

t()
t(c=4)
也会导致错误:

TypeError: t() takes exactly 2 arguments (0 given)
TypeError: t() got an unexpected keyword argument 'c'

如果参数不是可选的,则不要使用默认值

您仍然可以在调用中使用这些参数作为命名参数Python函数中的所有参数都命名为:

def t(a, b):
    return a+b

t(a=3, b=4)

请注意,传入错误的参数计数始终是运行时检查,而不是编译时检查。作为一种动态语言,在编译时不可能知道调用它时实际的对象是什么。

为什么要使用默认值?