python 中的参数魔法

Life is short ~

python中创建一个函数有关键字def

def hello(name):
    print "hello",name

这样就是一个函数啦,说说参数有哪几种方式:

tips:
1.函数内为参数赋新值不会改变外部的任何变量
2.函数内的变量最好跟外部的变量名字不同

1.位置参数:上面的例子就是位置参数
2.关键字参数:见名知意会有关键字
3.收集参数:一个参数接受多个值相当于 argv(from sys import argv)

def hello_again(name,pre="Mr."):
    print "hello",pre,name


result:
>>> hello_again("AshinLee")
hello Mr. AshinLee

但是关键字参数要在位置参数后面,否则:

>>> def hello_again(pre="Mr.",name,):
...     print "hello",pre,name
...
  File "<stdin>", line 1
SyntaxError: non-default argument follows default argument

当然关键字参数如果你给他赋值的话也是可以改变的,只是不赋值的时候给一个默认值

收集参数需要在位置参数的后面:

def hello_again(name,pre="Mr.",*num):
    print "hello",pre,name
    for n in num:
        print n

result:

>>> hello_again("AshinLee","Miss",1,2,3,5,6)
hello Miss AshinLee
1
2
3
5
6

Miss???? 黑人问号.jpg    演示下关键字参数是可以改变的那只是不输入的默认值

要注意的是如果关键字参数和收集参数混用,却有不输入关键字参数:

>>> hello_again("AshinLee",1,2,3,5,6)
hello 1 AshinLee
2
3
5
6
会出现和预期不符合的情况要注意

收集参数也可以收集关键字参数???

>>> def hello_again(name,*num,**age):
...     print name
...     print num
...     print age
...

result:
>>> hello_again("AshinLee",1,2,3,5,6,pre="Mr.",sex="male")
AshinLee
(1, 2, 3, 5, 6)
{'pre': 'Mr.', 'sex': 'male'}

*num **age 位置不可调动

以上这些就是python的参数魔法啦。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值