自定义函数第二步

参数的变化

1.位置参数

def test1(name,age):                                    #带两个固定参数
    print('姓名是:%s,年龄是%s' %(name,str(age)))
test1('时欺',17)                                        #调用函数时所传值必须与参数对应上
 
#执行结果: 姓名是:时欺,年龄是17

2.关键字参数

在前面的基础下继续执行

test1(name='时欺',age=17)    #所有参数都用'参数名=值'的方式指定
test1(age=17,name='时欺')    #可以不考虑参数位置
test1('时欺',age=17)         #部分指定时左边的可以不指定,从右边指定开始
test1(name='时欺',17)        #会报错,不支持从左边指定,右边不指定方式

3.默认值

def test1(name='',age=18):
    print('姓名是:%s,年龄是%s' %(name,str(age)))

test1(17)                          #默认情况是给第一个默认的参数赋值
test1()
test1('时欺',17)


#执行结果
姓名是:17,年龄是18
姓名是:,年龄是18
姓名是:时欺,年龄是17

自定义函数设置默认值,允许左边的参数没有默认值,而右边的有,反过来则不行

4.不定长参数*、**

传递多特征属性(传递的是元祖)

def watermelon(name,*attributes):              #带*的可以传递任意数量值的参数
    print(name)
    print(type(attributes))                    #验证类型
    description=''
    for get_t in attributes:                   #暗示集合数据类型进行操作
        description=''+get_t
    print(description)                         #打印属性说明

#调用自定义函数watermelon
watermelon('西瓜','甜','绿色','红瓤')
print('----------分割线-----------')
watermelon('无籽西瓜','没有子','测试属性','无限多个')

#执行结果:
西瓜
<class 'tuple'>
红瓤
----------分割线-----------
无籽西瓜
<class 'tuple'>
无限多个
传递任意数量键值对(传递的是字典)
def watermelon(name,**atributes):               #带**的为可以传递任意数量"键=值"的参数
    print(name)
    print(type(atributes))                      #验证attributes类型
    return atributes                            #返回字典类型对象
print(watermelon('西瓜',color='绿色',sweet='甜',shape='球形'))

#执行结果
西瓜
<class 'dict'>
{'color': '绿色', 'sweet': '甜', 'shape': '球形'}

传递元组 列表 字典值

传递元组/列表

def watermelong(name,attributes):
    print(name)
    print(type(attributes))                             #验证attributes类型
    return attributes                                   #返回对应类型对象

get_t=watermelong('西瓜',('甜','绿色','红瓤'))            #调用自定义函数  带元组传递
print(get_t)

get_t=watermelong('西瓜',['甜','绿色','红瓤'])            #调用自定义函数  带列表传递
print(get_t)
print('====================================')
get_t=watermelong('西瓜',{'color':'绿色','sweet':'甜','shape':'球形'})            #调用自定义函数  带字典传递
print(get_t)
#执行结果
西瓜
<class 'tuple'>
('甜', '绿色', '红瓤')
====================================
西瓜
<class 'list'>
['甜', '绿色', '红瓤']
====================================
西瓜
<class 'dict'>
{'color': '绿色', 'sweet': '甜', 'shape': '球形'}

传递列表/字典后的问题

自定义函数内获取从参数传递过来的列表\字典对象后,若在函数内部对他们的元素进行变化,会同步影响到函数外部传递前的变量元素.

def EditFrult(name,attributes):
    attributes[0]=attributes[0]*0.9               #打九折,修改列表元素
    return attributes

attri=[21,'甜', '绿色', '红瓤']    #21为价格

print(EditFrult('西瓜',attri.copy()))
print(attri)                                      #原始列表并未更改
执行结果
[18.900000000000002, '甜', '绿色', '红瓤']
[21, '甜', '绿色', '红瓤']

①列表元组都可以才用copy()方法实现对象的复制
②列表复制还可以用[:]方式获取列表对象的副本
③可用id函数验证列表对象地址的变化情况

函数传递对象总结

| 可变对象| 不可变对象 |
| ---- | ---- | ---- |
| 列表.字典 | 数字.字符串.元组 |
| 在函数里进行值修改,会变成新的对象,在内存产生新的地址 | 在函数里进行值修改,函数内外还是同一个对象,但是函数值同步发生变化 |

posted @ 2020-11-14 16:00  17。  阅读(84)  评论(0)    收藏  举报