What does this syntax mean in Python?

六月ゝ 毕业季﹏ 提交于 2020-01-11 10:37:31

问题


What does the comma in the declaration below mean? Does it define two variables at once?

resp, content = client.request(request_token_url, "GET")

回答1:


It creates a tuple. In this case, the tuple is of two variables, which get assigned the result from request().

request() returns a tuple, which is then automatically unpacked into the left-hand tuple during assignment.

If you had just

result = client.request(request_token_url, "GET")

that would assign the tuple directly to result. Then you would be able to access the response at result[0], the first value in the tuple, and the content would be in result[1].




回答2:


That's called tuple unpacking. In python, you can unpack tuples like this:

a, b = (1, 2)

See that on the right we have a tuple, packing values, and they are automatically "distributed" to the objects on the left.

If a function returns a tuple, in can be unpacked as well:

>>> def t():
...     return (1, 2)
... 
>>> a, b = t()
>>> a
1
>>> b
2

That's what's happening in your code.



来源:https://stackoverflow.com/questions/5616377/what-does-this-syntax-mean-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!