Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

** (Double Star) และ * (Star) ทำหน้าที่อะไรสำหรับ Parameters ใน Python?

ใน Python Function Argument ที่มี Single Asterisk (Star) นำหน้า ช่วยรับ Variable number of Arguments จาก Calling Environment

>> def function(*arg):
...     for i in arg:
...         print(i)
>>> function(1,2,3,4,5)
1
2
3
4
5

Argument ที่มี Double Asterisks (Stars) ใช้ใน Function Definition เมื่อต้องส่ง Variable number of Keyword Arguments ให้ฟังก์ชัน

>> def function(**arg):
...     for i in arg:
...         print(i, arg[i])
>>> function(a=1, b=2, c=3, d=4)
a 1
b 2
c 3
d 4

ใน Python 3 สามารถกำหนด Variable ด้วย Asterisk ใน Assignment Statement เพื่อเปิดใช้งาน Extended Unpacking ของ Iterables

>> a, *b = [1,2,3,4]
>>> a
1
>>> b
[2, 3, 4]
>>> a, *b, c = [1,2,3,4]
>>> a
1
>>> b
[2, 3]
>>> c
4