# 位置参数vs关键字参数

def printThese(a,b,c):   print(a, "is stored in a")   print(b, "is stored in b")   print(c, "is stored inc")printThese(1,2,3)"""1 is stored in a2 is stored in b3 is stored in c"""

def printThese(a,b,c):   print(a, "is stored in a")   print(b, "is stored in b")   print(c, "is stored inc")printThese(1,2)"""TypeError: printThese() missing 1 required positional argument: 'c'"""

def printThese(a,b,c=None):   print(a, "is stored in a")   print(b, "is stored in b")   print(c, "is stored inc")printThese(1,2)"""1 is stored in a2 is stored in bNone is stored in c"""

defprintThese(a=None,b=None,c=None):   print(a, "is stored in a")   print(b, "is stored in b")   print(c, "is stored inc")printThese(c=3, a=1)"""def printThese(a=None,b=None,c=None):   print(a, "is stored in a")   print(b, "is stored in b")   print(c, "is stored inc")printThese(c=3, a=1)"""1 is stored in aNone is stored in b3 is stored in c"""

# Splat运算符

a = [1,2,3]b = [*a,4,5,6]print(b) # [1,2,3,4,5,6]

# 如何使用*args和**kwargs

def printScores(student,*scores):   print(f"Student Name:{student}")   for score in scores:     print(score)printScores("Jonathan",100, 95, 88, 92, 99)"""Student Name: Jonathan10095889299"""

def printPetNames(owner,**pets):   print(f"Owner Name:{owner}")   for pet,name in pets.items():      print(f"{pet}:{name}")printPetNames("Jonathan", dog="Brock",fish=["Larry", "Curly", "Moe"],turtle="Shelldon")"""Owner Name: Jonathandog: Brockfish: ['Larry', 'Curly', 'Moe']turtle: Shelldon"""

·       利用*args和**kwargs作为标准化规范，把握好位置参数和关键字参数；

·       不能将**kwargs置于*args前，否则将产生错误；

·       清楚意识到关键字参数和**kwargs之间的冲突，该值本是传达**kwarg的意思，但是却不明就里的成为关键字参数的名称；

·       在函数调用时可以采用splat运算符。

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试