search
HomeBackend DevelopmentPython Tutorial元组的reference前加个星号是什么意思?

<span class="n">rect</span> <span class="o">=</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">screen</span><span class="o">.</span><span class="n">width</span><span class="p">(),</span> <span class="n">screen</span><span class="o">.</span><span class="n">height</span><span class="p">())</span>  
<span class="n">pixbuf</span> <span class="o">=</span> <span class="n">Gdk</span><span class="o">.</span><span class="n">pixbuf_get_from_window</span><span class="p">(</span><span class="n">rootwin</span><span class="p">,</span> <span class="o">*</span><span class="n">rect</span><span class="p">)</span><span class="c">#其中*rect是什么?</span>

回复内容:

我不会用PyGObject, 纯讨论星号参数这个语法.

类似问题(也许对你有帮助):
定义函数def func(**kwargs):print kwargs调用函数的时候 一定要func(a=1,b=2,c=3)这样吗?dict_t={'a':1,'b':2,'c':3}不能直接传字典吗?例如func(dict_t)。有什么好方法吗?

Python 参数知识(变量前加星号的意义)



咱们先搞定星号参数的含义以及2个例子:

在参数名之前使用1个星号,就是让函数接受任意多的位置参数。
2个星号就是接受任意多的关键字参数。


位置参数的举例:
假设你有这么个需求:把某函数接收到的除了第一个参数之外的所有参数输出。
元组的reference前加个星号是什么意思?


关键字参数的举例:
不管你传入多少个关键字参数, 我都能在kw里找到. 元组的reference前加个星号是什么意思?




接着来搞定这个类似于你在问题中的补充资料中的例子:


下面这个例子接受任意多的位置参数, 只输出第一个
元组的reference前加个星号是什么意思?(这里的 s 的类型是元组)


咱们定义一个新元组,待会扔给mean函数。
元组的reference前加个星号是什么意思?

2种用法的区别: 元组的reference前加个星号是什么意思?

元组的reference前加个星号是什么意思?可以看出,用了星号之后,就把元组 a 给解包(unpack)了。拆成一个个参数扔进去了。
上面这个例子等价于: 元组的reference前加个星号是什么意思?




================== 2013-2-26更新 ================

元组的reference前加个星号是什么意思?
s 是元组, 所以值不可修改。
我这里企图把位置参数里的第1个的值修改成5,然后输出。


使用元组看看:
元组的reference前加个星号是什么意思? 元组的reference前加个星号是什么意思?
我们换成列表看看: 元组的reference前加个星号是什么意思?
用字符串看看:
元组的reference前加个星号是什么意思?
我们这里拆了列表,元组,字符串变成位置参数再传进去。
可以看到不论如何。s 都是元组。
存储位置参数的这个 s 变量的类型并不取决于传入的参数的类型。




================= 再随便多写一些例子 =================:
普通函数:
元组的reference前加个星号是什么意思?
文艺函数: 元组的reference前加个星号是什么意思?





mean 遍历输出所有位置参数。s 是元组,别忘了。
咱们拆一下 列表 和 字符串。 元组的reference前加个星号是什么意思?
拆元组: 元组的reference前加个星号是什么意思?


拆字典: 元组的reference前加个星号是什么意思? 元组的reference前加个星号是什么意思?


拆字典它只会把[键]传进去,你是取不到值的。 元组的reference前加个星号是什么意思?



====== 要接受拆字典的值。函数形参用2个星号就行了。=======

这里的意思是: 把所有的关键字参数都扔给s (不包括位置参数)
元组的reference前加个星号是什么意思? 元组的reference前加个星号是什么意思?用函数时,
c前面的2个星号只是代表把 c 拆成关键字参数形式。

用的时候我们把字典拆成了关键字参数。
而函数接收的也是关键字参数。所以这个不会报错。


等价于这么用: 元组的reference前加个星号是什么意思?(没报错吧哈哈。)



如果你用函数的时候只给了1个星号:
元组的reference前加个星号是什么意思?
或是不给星号:
元组的reference前加个星号是什么意思?都是会报错的。


为什么??

放1个星号:
字典前面放个1个星号的确是拆开的意思。
1个星号拆字典会只是传入[键]。之前的一个例子证明过了。

问题是我们的函数mean它只接受关键字参数(回顾一下我们前面对mean的定义): 元组的reference前加个星号是什么意思?s 里面啥也没有啊。 输出啥? 报错!


不放星号:
不放星号就代表你把那个字典直接扔进去了。
问题是函数形参**s只接受关键字参数。
s 里面还是啥也没有, 报错!



(所有的举例所使用到的 函数名 参数名 都是随便取的, 没有什么特殊意义.)
感觉自己举例的还不是很好,如果哪里把你弄迷糊了。
欢迎在评论区讨论. :)



扩展阅读环节:

StackOverflow 上解释星号语法的问题:
syntax - Python: Once and for all. What does the Star operator mean in Python?

引用传值的问题:
Python: How do I pass a variable by reference? 表示把这个参数展开传进去。等价于:
pixbuf = Gdk.pixbuf_get_from_window(rootwin, 0, 0, screen.width(), screen.height())
调用(caller)
func(*sequence) Pass all objects in sequence as individual positional arguments
seq = [1,2,3]
func(*seq) -> func(1, 2, 3)

func(**dict) Pass all key/value pairs in dict as individual keyword arguments
dict = {'a' = 1, 'b' = 2}
func(*dict) -> func(a = 1, b = 2)

函数定义的
def func(*name) Matches and collects remaining positional arguments in a tuple
func(1, 2, 3) -> name = [1, 2, 3]

def func(**name) Matches and collects remaining keyword arguments in a dictionary
func(a = 1, b= 2) -> dict = {'a' = 1, 'b' = 2}

可参考 Chapter 18. Arguments python里星号有两种意思
1. 定义函数时
一般情况下,函数的参数接受指定个数的参数,比如
<span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="p">):</span>
    <span class="k">print</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span>
推荐一篇post:Understanding '*', '*args', '**' and '**kwargs' >>> def test(*args, **kwargs):
... print args, kwargs

>>>a={"a":1, "b":2}

>>> test(a)
({'a': 1, 'b': 2},) {}
>>> test(*a) #这里等同于test('a', 'b')
('a', 'b') {}
>>> test(**a) #这里等同于test(a=1, b=2)
() {'a': 1, 'b': 2}

一个星号就是把一个序列拆解传入,如果变量本身是字典,会退化成key的序列。
两个星号就是把key-value拆解传入。
姑且就当是语法糖吧。 搬运工:1.2 解压可迭代对象赋值给多个变量
这个解压非常dedicate,具有很多优雅的技巧。
总结如下:
(1)
完全不需要tem中间变量的交换:
a,b =b,a
(2)
有时候,你可能只想解压一部分,丢弃其他的值。对于这种情况Python并没有提供特殊的语法。 但是你可以使用任意变量名去占位,到时候丢掉这些变量就行了。
>>> data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]
>>> _, shares, price, _ = data
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you append elements to a Python array?How do you append elements to a Python array?Apr 30, 2025 am 12:19 AM

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

How do you debug shebang-related issues?How do you debug shebang-related issues?Apr 30, 2025 am 12:17 AM

The methods to debug the shebang problem include: 1. Check the shebang line to make sure it is the first line of the script and there are no prefixed spaces; 2. Verify whether the interpreter path is correct; 3. Call the interpreter directly to run the script to isolate the shebang problem; 4. Use strace or trusts to track the system calls; 5. Check the impact of environment variables on shebang.

How do you remove elements from a Python array?How do you remove elements from a Python array?Apr 30, 2025 am 12:16 AM

Pythonlistscanbemanipulatedusingseveralmethodstoremoveelements:1)Theremove()methodremovesthefirstoccurrenceofaspecifiedvalue.2)Thepop()methodremovesandreturnsanelementatagivenindex.3)Thedelstatementcanremoveanitemorslicebyindex.4)Listcomprehensionscr

What data types can be stored in a Python list?What data types can be stored in a Python list?Apr 30, 2025 am 12:07 AM

Pythonlistscanstoreanydatatype,includingintegers,strings,floats,booleans,otherlists,anddictionaries.Thisversatilityallowsformixed-typelists,whichcanbemanagedeffectivelyusingtypechecks,typehints,andspecializedlibrarieslikenumpyforperformance.Documenti

What are some common operations that can be performed on Python lists?What are some common operations that can be performed on Python lists?Apr 30, 2025 am 12:01 AM

Pythonlistssupportnumerousoperations:1)Addingelementswithappend(),extend(),andinsert().2)Removingitemsusingremove(),pop(),andclear().3)Accessingandmodifyingwithindexingandslicing.4)Searchingandsortingwithindex(),sort(),andreverse().5)Advancedoperatio

How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor