zoukankan      html  css  js  c++  java
  • Python 函数动态参数

    def show (*arg):
    print (arg,type(arg))
    show([11,22],[33])
    结果:([11, 22], [33]) <class 'tuple'>
    结论:一个*号传递的参数默认定义为元祖类型

    def show (**arg):
    print (arg,type(arg))
    show(k1='v1',k2='v2',k3='v3')
    结果:{'k1': 'v1', 'k3': 'v3', 'k2': 'v2'} <class 'dict'>定义
    结论:两个**号传递的参数默认定义为字典类型

    def show (*arg,**kwargs):
    print (arg,type(arg))
    print (kwargs,type(kwargs))
    show([11,22,33],[44],['a','b'],k1='v1',k2='v2')
    结果:

      ([11, 22, 33], [44], ['a', 'b']) <class 'tuple'>
      {'k2': 'v2', 'k1': 'v1'} <class 'dict'>

     结论:同时传递两个带*号的参数,在形参定义里,第一个形参只能是带一个*号,第二个形参只能是带两个*号,同时在参数传递的时候,第一个参数只能是普通的定义,第二个参数是字典的定义

    def show (*arg,**kwargs):
    print (arg,type(arg))
    print (kwargs,type(kwargs))
    #show([11,22,33],[44],['a','b'],k1='v1',k2='v2')

    li = [[11,22,33],[44],['a','b']]
    di = {'k1':'v1','k2':'v2'}
    show (li,di)

    show(*li,**di)

    结果:

      ([[11, 22, 33], [44], ['a', 'b']], {'k1': 'v1', 'k2': 'v2'}) <class 'tuple'>
      {} <class 'dict'>
      ([11, 22, 33], [44], ['a', 'b']) <class 'tuple'>
      {'k1': 'v1', 'k2': 'v2'} <class 'dict'>

     结论:通过第一种方式来传参数,python默认认为传到了第一个*号的形参那里,第二个*号不会接收参数。通过第二种方式来传递参数,才能将匹配的参数传给对应的形参。

      

      动态参数的应用

    s1 = '{0} is {1}'
    result = s1.format('alex','handsome')
    print(result)
    结果:alex is handsome

    s1 = '{0} is {1}'
    li = ['alex','handsome']
    result = s1.format(*li)
    print(result)
    结果:alex is handsome

    s1 = "{name} is {face}"
    result = s1.format(name='alex',face='handsome')
    print (result)
    结果:alex is handsome

    s1 = "{name} is {face}"
    dic = {'name':'alex','face':'handsome'}
    result = s1.format(**dic)
    print (result)
    结果:alex is handsome


  • 相关阅读:
    源码学习-出差有感
    《java数据结构与算法》系列之“快速排序"
    新征途
    命运总是喜欢开玩笑
    《java数据结构与算法》系列之“简单排序"-冒泡,选择,插入
    秒杀9种排序算法(JavaScript版)
    《进击的巨人》
    Noip2001 提高组 T3
    Noip2011 提高组 Day1 T1 铺地毯 + Day2 T1 计算系数
    Noip2012 提高组 Day1 T1 Vigenère 密码
  • 原文地址:https://www.cnblogs.com/python-study/p/5450113.html
Copyright © 2011-2022 走看看