函数的默认参数是可变不可变引起的奇怪返回值

def selfAdd(a):
    a += a
a_int = 1
print('a_int1:',a_int)
selfAdd(a_int)
print('a_int2:',a_int)
输出结果:
a_int1: 1
a_int2: 1

a_list =[1,2]
print('a_list1:',a_list)
selfAdd(a_list)
print('a_list2;',a_list)
输出结果:
a_list1: [1, 2]
a_list2; [1, 2, 1, 2]

'''Python中函数的参数是引用传递(注意不是值传递). 对于不可变类型(数值int,字符串string,元祖tuple),
因变量不能更改,所以运算不会影响到
变量自身;  而对于可变类型(列表,字典)来说,函数体运算可能会更改传入的参数变量'''
def extendList(val, list_test=[]):
    list_test.append(val)
    print('list_test: >>',list_test)
    return list_test
list_test1 = extendList(10)  # 
print ("list_test1_first= %s" % list_test1)
list_test2 = extendList(123,[]) #
list_test3 = extendList('a') #
print ("list_test1 = %s" % list_test1)
print ("list_test2 = %s" % list_test2)
print ("list_test3 = %s" % list_test3)
输出:
list_test: >> [10]
list_test1_first= [10]
list_test: >> [123]
list_test: >> [10, 'a']
list_test1 = [10, 'a']
list_test2 = [123]
list_test3 = [10, 'a']

位置参数和*

在*参数后面还有参数市,一定要是位置参数指明age=?,并且要放在最后, 如果参数中出现 *users,传递的参数就可以不再是固定个数,传过来的所有参数打包元祖

def send_alert(msg,*users,age): # (['alex','xxx','iiii'],) --> ('alex','xxx','iiii')
    for u in users:
        print('报警发送给',u)
send_alert('别他么狼了',*['alex','xxx','iiii'],age=33)
输出: 报警发送给 alex
报警发送给 xxx
报警发送给 iiii


send_alert('别他么狼了',['alex','xxx','iiii'],age=34)
输出:报警发送给 ['alex', 'xxx', 'iiii']


send_alert("alex","rain",'eric',age=22)
输出:报警发送给 rain
报警发送给 eric
def send_alert(msg,*args):

    print('sending msg ....',msg,args)

    if args:
        print(args[0])

send_alert('cpu alert...')
send_alert('cpu alert...','email')
send_alert('cpu alert...','weixin',1)
输出:
sending msg .... cpu alert... ()
sending msg .... cpu alert... ('email',)
email
sending msg .... cpu alert... ('weixin', 1)
weixin
posted @ 2021-04-19 22:54  ty1539  阅读(58)  评论(0编辑  收藏  举报