Python学习笔记(8)函数、位置参数、可变参数、关键字参数

一、函数

  python的代码可以通过方法来封装一些代码,以便于后期的使用,定义格式:def  函数名(参数):

  注意:方法只有在被调用时,才会被执行

def hello():#定义函数名为hello的方法,不用传参即可调用
    print('hello')
    print('sdfsdf')

#方法只有在调用时才会被执行
def write_file(file_name,content):
    #定义写文件的方法,file_name和content为位置参数
    with open(file_name,'w',encoding='utf-8') as f:
        f.write(content)

#可使用return返回方法的返回值
def read_file(file_name):
    with open(file_name,encoding='utf-8') as f:
        content = f.read()
        return content
result = read_file('修改文件.py')
#调用方法,使用result变量接收方法的返回值,返回值为读取文件内容

  

二、函数参数

  函数参数分为:位置参数、默认值参数、可变参数、关键字参数

  注意:当return返回多个值时,会自动将值包装成元组tuple返回

位置参数

def b(name,age): #必填参数,位置参数
    print("name:",name)
    print("age:",age)
    return name,age
print(b("tang",18))

  返回结果:

name: tang
age: 18
('tang', 18)

  

默认值参数

def op_file(file,content=None): #默认值参数
    with open(file,'a+',encoding='utf-8') as f:
        if content:#当content有内容时,执行写文件操作
            f.write(str(content))
        else:#当content无内容时,执行写文件操作
            f.seek(0)
            result = f.read()
            return result

  

可变参数def  函数名(*args):--------------------------参数默认将多个传参包装为元组tuple进行传递

def send_sms(*args):#可变参数
    print(args)
send_sms(1,2,3,3,4,24,)
send_sms([1,2,3],[1,3],{"name":"age"},(1,2,4))
l=[1,2,4,5,6] #----------------------可传入list,使用*list来传入参数,系统自动封装为tuple传参
s='asdss'  #-------------------------可传入字符串,使用*s来传入参数,系统自动封装为tuple传参
send_sms(*l)
send_sms(*s)

  返回结果:

(1, 2, 3, 3, 4, 24)
([1, 2, 3], [1, 3], {'name': 'age'}, (1, 2, 4))
(1, 2, 4, 5, 6)
('a', 's', 'd', 's', 's')

  

关键字参数 def 函数名(**kwargs):--------------------关键字参数需要传入一个字典类型,系统将入参自动封装为

def t(**kwargs):#关键字参数,传入的必须得指定关键字
    print(kwargs)
t(name="tang",age=18)  #第一种传参方法:直接使用变量名=....
list={"name":"lei",'age':10}#第二种传参方法:使用字典传参,参数使用**list格式
t(**list)

  返回结果:

 

{'name': 'tang', 'age': 18}
{'name': 'lei', 'age': 10}

 

三、多种类型参数混合使用顺序

#必填参数、默认值、可变参数、关键字参数 必须得按照这个顺序来
#必填参数必须写到默认值参数前面
#默认参数必须在可变参数前面
#可变参数必须在关键字参数前面

def test(name,content=None,*args,**kwargs):
    print(name)
    print(content)
    print(args)
    print(kwargs)

  

posted @ 2020-05-05 13:32  布谷鸟的春天  阅读(289)  评论(0编辑  收藏  举报