Python 函数定义中带星号变量的默认初始化

Python 函数定义中带星号变量的默认初始化,python,function,variables,initialization,default,Python,Function,Variables,Initialization,Default,众所周知,为了在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)):

众所周知,为了在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)
来切换语法,但遇到了相同的错误。是否可以将带星号的变量初始化为默认值?

星型变量是非标准变量,用于允许具有任意长度的函数

*variables是包含所有位置参数的元组(通常称为args)

**variables是一个包含所有命名参数的字典(通常称为kwargs)

它们总是在那里,如果没有提供,它们就空着。您可以根据参数的类型测试字典或元组中是否有值,并对其进行初始化

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:)中阅读有关这些参数的更多信息您可以在函数的开头执行检查,以确定
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")

这个问题可能对你有帮助:嗯。我想我只是想得太多了,谢谢你!args和kwargs最初也让我有点困惑:)