为什么有些Python函数在参数列表周围有一组额外的括号?

Wil*_*mKF 11 python arguments parentheses

我见过一些像这样编写的Python函数:

def get_year((year,prefix,index,suffix)):
  return year
Run Code Online (Sandbox Code Playgroud)

如果没有像这样的额外括号,它与其他函数有何不同(如果有的话):

def do_format(yr,pfx,id,sfx):
  return "%s %s %s/%s"%(yr, id, pfx, sfx)
Run Code Online (Sandbox Code Playgroud)

或者它只是风格的品味问题,或者如果它们不同,可以将get_year()重写为do_format()或反之亦然,而不影响现有调用者的语法?

Roh*_*ain 10

第一个函数采用单个元组参数,而第二个函数采用4个参数.您可以单独传递这些参数,也可以作为带有splat运算符的元组,将元组解压缩为单个参数.

例如:

# Valid Invocations
print do_format(*('2001', '234', '12', '123'))  # Tuple Unpacking
print do_format('2001', '234', '12', '123')     # Separate Parameter
print get_year(('2001', '234', '12', '123'))

# Invalid invocation. 
print do_format(('2001', '234', '12', '123'))   # Passes tuple
Run Code Online (Sandbox Code Playgroud)


Joh*_*n Y 7

get_year示例中的函数使用自动解压缩的元组参数(这是Python 3中的功能).要调用它,您可以为其指定一个参数,该参数应该是包含四个值的序列.

# Invocation
my_input = [2013, 'a', 'b', 'c'] # sequence does NOT have to be a tuple!
my_year = get_year(my_input) # returns 2013
Run Code Online (Sandbox Code Playgroud)

要为Python 3重写它,但不要改变调用(换句话说,不要破坏调用的现有代码get_year):

def get_year(input_sequence):
    year, prefix, index, suffix = input_sequence
    return year
Run Code Online (Sandbox Code Playgroud)

以上就是元组解包为你自动做的事情.在这种特殊情况下,你可以简单地写

def get_year(input_sequence):
    return input_sequence[0]
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请阅读PEP 3113.