简体   繁体   English

“ foo(* a)”在Python中如何工作?

[英]How does “foo(*a)” work in Python?

Just switched from C++ to Python, and found that sometimes it is a little hard to understand ideas behind Python. 刚从C ++切换到Python,发现有时很难理解Python背后的想法。

I guess, a variable is a reference to the real object. 我想,变量是对实际对象的引用。 For example, a=(1,2,5) meaning a -> (1,2,5), so if b=a, then b and a are 2 references pointing to the same (1,2,5). 例如,a =(1,2,5)表示a->(1,2,5),因此,如果b = a,则b和a是2个引用,指向相同的(1,2,5)。 It is a little like pointers in C/C++. 它有点像C / C ++中的指针。

If I have: 如果我有:

def foo(a,b,c):
  print a,b,c

a=(1,3,5)
foo(*a)

What does * mean here? *在这里是什么意思?

Looks like it expands tuple a to a[0], a[1] and a[2]. 看起来它将元组a扩展为a [0],a [1]和a [2]。 But why print(*a) is not working while print(a[0],a[1],a[2]) works fine? 但是,为什么在print(a[0],a[1],a[2])工作正常的情况下print(a[0],a[1],a[2]) print(*a)无法工作?

You seem to already understand that the asterisk is for argument unpacking . 您似乎已经了解星号是用于参数解包的 So the only confusion is about the print statement itself. 因此,唯一的困惑是关于print语句本身。

In python 3, print(*a) works fine: 在python 3中, print(*a)可以正常工作:

>>> a=(1,3,5)
>>> print(*a)
1 3 5

In Python 2, however, it does not: 但是,在Python 2中,它不会:

>>> a=(1,3,5)
>>> print(*a)
  File "<stdin>", line 1
    print(*a)
          ^
SyntaxError: invalid syntax

This is because print is not a function in Python 2, so Python 2 does not interpret the asterisk as argument unpacking instructions. 这是因为print在Python 2中不是函数,因此Python 2不会将星号解释为参数解包指令。 In fact, print in Python 2 does not require parentheses. 实际上,在Python 2中print不需要括号。 Wrapping a value with parentheses doesn't mean anything. 用括号括起来的值没有任何意义。 (a) and a are the same. (a)a相同。 (Whereas (a,) is a tuple with one member.) So print (a) and print a are also the same. (而(a,)是具有一个成员的元组。)因此print (a)print a也相同。

You can, however, override the print statement with a print function from the future : 但是,您可以在以后使用print函数覆盖print语句:

>>> from __future__ import print_function
>>> print(*a)
1 3 5

It doesn't work in Python 2 because there, print is not a function . 它在Python 2中不起作用,因为那里print不是一个函数 It is a statement. 这是一个声明。

But, in Python 3, it will work as expected, because print is a function . 但是,在Python 3中,它将正常运行,因为print是一个函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM