函数的参数设定

1.def test(x, y):

     print(x, y)

test(y=1, x=2)

test(2 , y=1)    #位置参数一定要在关键字参数的前面 

def test(x, y, z):

    print(x, y, z)

test(2, z=1, y=2)

2.默认参数

def test(x, y=2):   #定义关键字参数时,位置参数要在关键字参数之前 不能写成 test(y=2, x)

     print(x, y) 

 

test(2)

test(2,2)

3.传递不固定的形参 

def test(*args):
      print(test)

test(1, 2, 3, 4, 5, 6)

test(*[1, 2, 3, 4, 5, 6])  #*args = *[1, 2, 3, 4, 5] #传入一个元组

test([1, 2, 3, 4, 5, 5])    #传入一个列表 为单独的一个变量 

def test(x, *args):

      print(x)

      print(args)

4. 传递字典 

def test3(name, **kwargs):

      print(name)

      print(kwargs)

test('alex', age=18, sex='m')

def test3(name, **kwargs):

      print(name)

      print(kwargs['age'])

      print(kwargs['sex'])

test('alex', age=18, sex='m')

5.混合编程

def test4(name, *args, age = 18, **kwargs):

       print(name)

       print(age)

       print(kwargs)

       logger('Test4')

def logger(source):

       print('from %s' %source)

test('alex', 18, age = 18, sex = 'm', hobby = 'tesla)

 

转载于:https://www.cnblogs.com/my-love-is-python/p/9036811.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值