函数的参数:
# -*-coding:utf-8 -*-
__author__ = ‘xiaojiaxin‘
__file_name__ = ‘函数参数‘
def print_info(name,age):
print("name is %s"%name)
print("name is %d"%age)
#必备参数,关键字参数
print_info("11",12)
print_info(age=19,name="xjx") #关键字参数,不用考虑顺序
#print(print_info("1",18))
#默认参数
def print_info2(name,sex="f"):
print("name is %s"%name)
print("name is %s"%sex)
print_info2("jiaxin") #默认参数在调用的时候可以不写
# name is jiaxin
# name is f
#不定长参数
def add(*args): #*表示接受不定长的参数
print(args)
sum=0
for i in args:
sum+=i
print(sum)
add(1,2,3)
# (1, 2, 3) #实际上是把不定长参数变成元组
# 6
#可能需要一个函数能处理比当初声明时更多的参数,这些参数叫做不定长参数,声明时不会命名
def print_info(name,age,sex,**kwargs): #**可以输入未命名的键值对
print("Name: %s"%name)
print("Age: %d"%age)
print("Sex: %s"%sex)
print(kwargs)
print_info("jiaxin",18,"female",job="it",hobby="swimming")
# {‘job‘: ‘it‘, ‘hobby‘: ‘swimming‘} 未命名的参数放入字典中
#*args是非关键字参数,用于元组,**kw是关键字参数,用于字典
def print_info(*args,**kwargs): #**可以输入未命名的键值对
print(args)
print(kwargs)
for i in kwargs: #遍历方法
print(i,":",kwargs[i])
#不定长参数位置:*args的只能放在左边,**kwargs有命名的只能放在右边,有默认参数放最左边
print_info(1,2.4,name="jiaxin",age=18,sex="female",job="it",hobby="swimming")
# (1,2.4)
# {‘name‘: ‘jiaxin‘, ‘age‘: 18, ‘sex‘: ‘female‘, ‘job‘: ‘it‘, ‘hobby‘: ‘swimming‘}
# name : jiaxin
# age : 18
# sex : female
# job : it
# hobby : swimming
#位置从左到右:关键参数 默认参数 *args参数,**kwargs参数
大家对内容有任何问题,欢迎留言,定在第一时间解答,谢谢大家!
原文地址:http://blog.51cto.com/10777193/2072837