第二模块 3.5 函数的参数
Posted kissfire008
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第二模块 3.5 函数的参数相关的知识,希望对你有一定的参考价值。
1 位置参数, 默认参数 位置参数> 关键参数/默认参数
def register(name, age, major, country="CN"): # 默认参数,需要显示所有参数后面, 先找位置参数, 再找默认参数, """ 学籍注册程序 :param name: str :param age: int :param major: str, CS :param country: JP, CN, US :return: """ info = """ ----------------你的注册信息 ------------- name: %s age:%s major:%s country:%s """ %(name, age, major, country) print(info) register("张三",22,"CS") register("李四",18,"Math") register("Mike",20,"CS","US")
2 关键参数
def register(name, age, major="CS", country="CN"): # 默认参数,需要显示所有参数后面, 先找位置参数, 再找默认参数, """ 学籍注册程序 :param name: str :param age: int :param major: str, CS :param country: JP, CN, US :return: """ info = """ ----------------你的注册信息 ------------- name: %s age:%s major:%s country:%s """ %(name, age, major, country) print(info) register(age=22,name = "alex") #关键参数,位置参数在前, 关键参数在后
3 非固定参数 在定义函数时, 不确定后面调用时, 会传递多少个参数进来
def register(name, age, major="CS", country="CN",*args, **kwagrgs): # 额外传输进来的非固定参数 """ 学籍注册程序 :param name: str :param age: int :param major: str, CS :param country: JP, CN, US :return: """ info = """ ----------------你的注册信息 ------------- name: %s age:%s major:%s country:%s """ %(name, age, major, country) print(info) print(args, kwagrgs.get("addr")) register(age=22,name = "alex",sex = "M", phone = 13012345564) #关键参数,位置参数在前, 关键参数在后 register(age=22,name = "jack",sex = "M", addr = "沙河") register("Mike",20,"CS","US")
def register(name, *args,**kwargs): print(name, args,kwargs) register("Alex",22, "Math", sex = "M")
打印结果是:
Alex (22, ‘Math‘) {‘sex‘: ‘M‘}
本小结练习题答案:
def register(name, age, hobbie,sex = "M",): info = """ -------------info------------ Name:%s Age: %s Sex: %s Hobbie: %s """ %(name, age, sex, hobbie) print(info) register(name="Alex", age=22, hobbie= "大保健") register(name="Jack", age=26, hobbie= "学习")
以上是关于第二模块 3.5 函数的参数的主要内容,如果未能解决你的问题,请参考以下文章
如何使用模块化代码片段中的LeakCanary检测内存泄漏?