zoukankan      html  css  js  c++  java
  • 【Python学习】函数参数传递方法四种(位置,关键字,默认值,包裹位置,包裹关键字传递)

    位置传递:
    --coding:utf-8--
    def send(name,address):
    return 'package is sent to %s, located in %s' %(name, address)
    print(send('winnie','shanghai'))

    关键字传递
    复制代码
    def run(name,length, date):
    return '%s ran %s on %s' %(name,length,date)

    关键字传递时,可以无视参数顺序,名字对了就行。
    print(run(length = '5km',date ='11/29/2016',name = 'winnie'))

    关键字和位置混用,但要注意位置参数要出现在关键字前面。 如果不,那编译器不知道除了几个有名字的,位置的顺序。
    print(run('winnie',length = '5km',date ='11/29/2016'))
    复制代码
    winnie ran 5km on 11/29/2016
    winnie ran 5km on 11/29/2016
    [Finished in 0.2s]

    默认值参数
    3. 默认值参数: 可以给出参数默认值
    我们跑团每周二的例行约跑
    def runWeekly(name,length, time = 'Tuesday 5:00PM'):
    return '%s ran %s on %s' %(name,length,time)
    调用:

    print(runWeekly('jin','5km'))
    print(runWeekly('jin','5km','Wednesday'))
    print(runWeekly('jin',time = '5km','Wednesday')) #Error

    File "C:pytestSele em1111.py", line 20
    print(runWeekly('jin',time = '5km','Wednesday'))
    SyntaxError: non-keyword arg after keyword arg
    [Finished in 0.2s with exit code 1]
    4. 包裹传递

    复制代码

    1. 包裹传递 (/**)
      参数被 collect收集,type: tuple
      def subselect(
      collect):
      print collect
      print type(collect)

    参数被 aa收集,type: dict
    def packing(**aa):

    print test

    print type(aa)
    print aa
    复制代码
    调用:

    subselect(['ppe-test-1','dddd'])
    packing(a=1,b=2,sub=[11,22])
    输出:

    <type 'tuple'>
    <type 'dict'>
    {'a': 1, 'b': 2, 'sub': [11, 22]}
    [Finished in 0.2s]
    5. 解包

    复制代码

    5.Unpacking with /*
    tuple1 = ['test1','test2','test3']
    dictionary1 = {'at':'88wi','b':'secondParam','third':'winnie'}
    print 'dictionary1 ', dictionary1
    def useDict(at,b,third):
    print at , b ,third
    useDict(**dictionary1) #把字典参数解包 此时相当于关键字参数传递 名字和函数定义的参数名必须要一一对应
    useDict(*tuple1) #把元组解包 此时相当于位置参数传递
    复制代码

  • 相关阅读:
    每天干攻防,都不会写驱动了
    SSD 坏了
    据说英雄联盟要出新皮肤了
    随便写点什么,证明我还活着,VS2010出现的问题
    ida 符号路径设置
    搭建一个自己的SVN服务器
    nginx+keepalived互为主主高可用配置
    nginx+keepalived主从高可用配置
    Lnamp的高级网站架构+动静分离+反向代理
    Nginx+PHP(FastCGI)高性能服务器加载redis+memcache模块
  • 原文地址:https://www.cnblogs.com/wang1018-kuiying/p/14500523.html
Copyright © 2011-2022 走看看