python带星号函数
默认值函数参数。这种函数定义时,第一个有默认值的参数后的每一个参数都必须提供默认值。传参时,可以直接传参,也可以以“默认值参数名=value”的形式传参。
单星号函数参数。单星号函数参数接收的参数组成一个元组。
单星号参数,把接收的参数作为元组,如果直接传元组类型的值,则传递的元组值作为了星号参数的元组中的一个元素。若要把元组值就作为星号参数的参数值,在元组值前加上“*”即可,不过此时,就不能在加了“*”的元组后,追加任何值了。
双星号函数参数。双星号函数参数接收的参数组成一个字典。必须采用默认值传参的“args = value”的方式。同时,“=”前的字段成了字典的键,“=”后的字段成了字典的值。即,双星号参数接收的参数作为字典。若想把字典值就作为星号参数的参数值,那么该怎么办呢?同单星号参数,在字典值前加上“**”,同时其后不能添加任何值。

#!/usr/bin/python
def singalStar(common, *rest):
print("Common args: ", common)
print("Rest args: ", rest)
def doubleStar(common, **double):
print("Common args: ", common)
print("Double args: ", double)
def singalAndDoubleStar(common, *single, **double):
print("Common args: ", common)
print("Single args: ", single)
print("Double args: ", double)
def defaultValueArgs(common, defaultStr = "default", defaultNum = 0):
print("Common args", common)
print("Default String", defaultStr)
print("Default Number", defaultNum)
if __name__ == "__main__":
defaultValueArgs("Test")
defaultValueArgs("Test", "defaultqqq", defaultNum = 1)
singalStar("hello")
singalStar("hello", "world", 000)
singalStar("hello", ("world", 000))
singalStar("hello", ("world", 000), {123: 123})
singalStar("hello", *("world", 000))
# singalStar("hello", *("world", 000), "123") #error
doubleStar("hello")
doubleStar("hello", x = "Test", y = 24)
doubleStar("hello", **{"name": "Test", "age": 24})
# doubleStar("hello", {"name": "Test", "age": 24}) #error
singalAndDoubleStar("hello")
singalAndDoubleStar("hello", "world", 000)
singalAndDoubleStar("hello", "world", 000, {"name": "Test", "age": 24})
singalAndDoubleStar("hello", "world", 000, **{"name": "Test", "age": 24})
singalAndDoubleStar("hello", ("world", 000), {"name": "Test", "age": 24})
# singalAndDoubleStar("hello", *("world", 000), {"name": "Test", "age": 24}) #error
singalAndDoubleStar("hello", *("world", 000), **{"name": "Test", "age": 24})