zoukankan      html  css  js  c++  java
  • python开发_函数的参数传递

    在这个用例中,我们要讨论的是关于函数的传参问题
    我所使用的python版本为3.3.2

    对于函数:

    1 def fun(arg):
    2     print(arg)
    3 
    4 def main():
    5     fun('hello,Hongten')
    6 
    7 if __name__ == '__main__':
    8     main()

    当我们传递一个参数给fun()函数,即可打印出传递的参数值

    信息。

    这里打印的信息为:

    hello,Hongten

    对于下面的用例:

    1 def fun(a=1, b=None, c=None, *args):
    2     print('{0},{1},{2},{3}'.format(a, b, c, args))
    3 
    4 def main():
    5     fun(a='one')
    6     fun('one')
    7 
    8 if __name__ == '__main__':
    9     main()

    当传递的参数为:fun(a='one')和fun('one')这样的传参都是把值复制给参数a,所有两种传参的效果是一样的:

    one,None,None,()
    one,None,None,()

    当然我们也可以给参数:b,c,*args赋值

    如:

    1 def fun(a=1, b=None, c=None, *args):
    2     print('{0},{1},{2},{3}'.format(a, b, c, args))
    3 
    4 def main():
    5     fun('one',1,2,('hongten'))
    6 
    7 if __name__ == '__main__':
    8     main()

    这样我们就给参数:b,c,args赋上了值

    运行效果:

    one,1,2,('hongten',)

    在上面的列子中,我们不能绕开参数*args前面的参数a,b,c给*args复制:

    如:

    1 def fun(a=1, b=None, c=None, *args):
    2     print('{0},{1},{2},{3}'.format(a, b, c, args))
    3 
    4 def main():
    5     fun(args=('hongten'))
    6 
    7 if __name__ == '__main__':
    8     main()

    运行效果:

    Traceback (most recent call last):
      File "E:/Python33/python_workspace/test_fun.py", line 21, in <module>
        main()
      File "E:/Python33/python_workspace/test_fun.py", line 18, in main
        fun(args=('hongten'))
    TypeError: fun() got an unexpected keyword argument 'args'

    但是对于参数:a,b,c来说,是可以使用这样的方式进行赋值

    如:

    1 def fun(a=1, b=None, c=None, *args):
    2     print('{0},{1},{2},{3}'.format(a, b, c, args))
    3 
    4 def main():
    5     fun(c=('hongten'), b=2, a=[1,2,3])
    6 
    7 if __name__ == '__main__':
    8     main()

    运行效果:

    [1, 2, 3],2,hongten,()
  • 相关阅读:
    49. 字母异位词分组
    73. 矩阵置零
    Razor语法问题(foreach里面嵌套if)
    多线程问题
    Get json formatted string from web by sending HttpWebRequest and then deserialize it to get needed data
    How to execute tons of tasks parallelly with TPL method?
    How to sort the dictionary by the value field
    How to customize the console applicaton
    What is the difference for delete/truncate/drop
    How to call C/C++ sytle function from C# solution?
  • 原文地址:https://www.cnblogs.com/hongten/p/hongten_python_params.html
Copyright © 2011-2022 走看看