函数定义中带星号的变量的默认初始化
Default Initialization of Starred Variables within the Definition of a Function
众所周知,为了在 Python 中的函数内为变量设置默认值,使用以下语法:
def func(x = 0):
if x == 0:
print("x is equal to 0")
else:
print("x is not equal to 0")
因此,如果这样调用函数:
>>> func()
结果是
'x is equal to 0'
但是当对加星号的变量使用类似的技术时,例如,
def func(*x = (0, 0)):
它会导致语法错误。我也尝试通过 (*x = 0, 0)
来切换语法,但遇到了同样的错误。是否可以将带星标的变量初始化为默认值?
star 变量是非标准变量,旨在允许具有任意长度的函数
*variables 是一个包含所有位置参数的元组(通常命名为 args)
**variables 是一个包含所有命名参数的字典(通常命名为 kwargs )
它们会一直存在,如果提供 none 则只是空的。您可以根据参数类型测试值是否在字典或元组中并对其进行初始化。
def arg_test(*args,**kwargs):
if not args:
print "* not args provided set default here"
print args
else:
print "* Positional Args provided"
print args
if not kwargs:
print "* not kwargs provided set default here"
print kwargs
else:
print "* Named arguments provided"
print kwargs
#no args, no kwargs
print "____ calling with no arguments ___"
arg_test()
#args, no kwargs
print "____ calling with positional arguments ___"
arg_test("a", "b", "c")
#no args, but kwargs
print "____ calling with named arguments ___"
arg_test(a = 1, b = 2, c = 3)
默认情况下,带星号的变量的值为空元组 ()
。虽然由于带星号的参数的工作方式无法更改该默认值(tl;dr:Python 分配未加星号的参数,如果有的话,并将其余参数收集在元组中;您可以阅读更多关于它们的信息相关 PEP 3132 中的示例:https://www.python.org/dev/peps/pep-3132/) 您可以在函数的开头实施检查以查明 x
是否为空元组,然后相应地更改它。您的代码看起来像这样:
def func(*x):
if x == (): # Check if x is an empty tuple
x = (0, 0)
if x == 0:
print("x is equal to 0")
else:
print("x is not equal to 0")
众所周知,为了在 Python 中的函数内为变量设置默认值,使用以下语法:
def func(x = 0):
if x == 0:
print("x is equal to 0")
else:
print("x is not equal to 0")
因此,如果这样调用函数:
>>> func()
结果是
'x is equal to 0'
但是当对加星号的变量使用类似的技术时,例如,
def func(*x = (0, 0)):
它会导致语法错误。我也尝试通过 (*x = 0, 0)
来切换语法,但遇到了同样的错误。是否可以将带星标的变量初始化为默认值?
star 变量是非标准变量,旨在允许具有任意长度的函数
*variables 是一个包含所有位置参数的元组(通常命名为 args)
**variables 是一个包含所有命名参数的字典(通常命名为 kwargs )
它们会一直存在,如果提供 none 则只是空的。您可以根据参数类型测试值是否在字典或元组中并对其进行初始化。
def arg_test(*args,**kwargs):
if not args:
print "* not args provided set default here"
print args
else:
print "* Positional Args provided"
print args
if not kwargs:
print "* not kwargs provided set default here"
print kwargs
else:
print "* Named arguments provided"
print kwargs
#no args, no kwargs
print "____ calling with no arguments ___"
arg_test()
#args, no kwargs
print "____ calling with positional arguments ___"
arg_test("a", "b", "c")
#no args, but kwargs
print "____ calling with named arguments ___"
arg_test(a = 1, b = 2, c = 3)
默认情况下,带星号的变量的值为空元组 ()
。虽然由于带星号的参数的工作方式无法更改该默认值(tl;dr:Python 分配未加星号的参数,如果有的话,并将其余参数收集在元组中;您可以阅读更多关于它们的信息相关 PEP 3132 中的示例:https://www.python.org/dev/peps/pep-3132/) 您可以在函数的开头实施检查以查明 x
是否为空元组,然后相应地更改它。您的代码看起来像这样:
def func(*x):
if x == (): # Check if x is an empty tuple
x = (0, 0)
if x == 0:
print("x is equal to 0")
else:
print("x is not equal to 0")