python默认值、关键字参数

来源:互联网 发布:c语言游戏 编辑:程序博客网 时间:2024/06/05 15:09

给参数设置默认值非常有用。

def passion(name,location=" 中国"):    return name+locations = 'a23foiwe9owef0wfia2'ret1 = passion("thinking",)ret2 = passion("thinking"," 上海 浦东")print("ret1=%s"%ret1)print("ret2=%s"%ret2)
打印结果为:

ret1=thinking 中国
ret2=thinking 上海 浦东

从第一个调用passion方法的语句结果中可以看出,当只传一个参数时,location的值取默认值: 中国


#!/usr/bin/env python#-*-coding:utf-8-*-def get_per_info(name="刘十三",location=" 在中国"):    return name+locationper_info = get_per_info(location=" 在美国")per_info2 = get_per_info(name="快刀")print("per_info=%s"%per_info)print("per_info2=%s"%per_info2)

打印值是:

per_info=刘十三 在美国
per_info2=快刀 在中国


关键字参数传值可以不用考虑参数的顺序,使程序的可读性更强。


1 0