Python里的变长参数理解

元组(Tuple)变长参数:适用于未知参数的数量不固定,但在函数中使用这些参数无需知道这些参数的名字的场合。
    在函数定义中,元组变长参数使用“*” 标记
 

def show_message(meassage, *tupleName):
    for name in tupleName:
        print(meassage, ":", name)

if __name__ == '__main__':
    show_message("Good moring", "June", "Jack", "Jim")

字典(Dictionary)变长参数:适用于未知参数的数量不固定,而且在函数中使用这些参数时需要知道这些参数的名字的场合。
在函数定义中,字典变长参数用“**” 标记

#python 2
def check_book(**dictParam):
    if dictParam.has_key('Price'):
        price = int (dictParam['Price'])
        if price > 100:
            print("--------I want Buy this Book----------")
    print("The book information are as follow")
    for key in dictParam.keys():
        print(key, ":", dictParam[key])
    print("")

if __name__ == '__main__':
    check_book(author = 'June', Title = "Hello world")
    check_book(author = "Luenci", Title = "Python Study", data = "2018-9-25", Price = 125)
    check_book(data = '2018-9-25', Title = "Cooking Book", Price = 19)
    check_book(author = "Jine", Title = "How to keep healthy")
    check_book(category = 'Finance', name = 'spiderman', Price = 12)

猜你喜欢

转载自blog.csdn.net/Luenci379/article/details/82842169