python函數之參數傳遞

來源:互聯網
上載者:User
在這個用例中,我們要討論的是關於函數的傳參問題

我所使用的python版本為3.3.2

對於函數:

1

2

3

4

5

6

7

8

def fun(arg):

print(arg)

def main():

fun('hello,Hongten')

if __name__ == '__main__':

main()

當我們傳遞一個參數給fun()函數,即可列印出傳遞的參數值資訊。

這裡列印的資訊為:

hello,Hongten

對於下面的用例:

1

2

3

4

5

6

7

8

9

def fun(a=1, b=None, c=None, *args):

print('{0},{1},{2},{3}'.format(a, b, c, args))

def main():

fun(a='one')

fun('one')

if __name__ == '__main__':

main()

當傳遞的參數為:fun(a='one')和fun('one')這樣的傳參都是把值複製給參數a,所有兩種傳參的效果是一樣的:

one,None,None,()

one,None,None,()

當然我們也可以給參數:b,c,*args賦值

如:

1

2

3

4

5

6

7

8

def fun(a=1, b=None, c=None, *args):

print('{0},{1},{2},{3}'.format(a, b, c, args))

def main():

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

if __name__ == '__main__':

main()

這樣我們就給參數:b,c,args賦上了值

運行效果:

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

在上面的列子中,我們不能繞開參數*args前面的參數a,b,c給*args複製:

如:

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

運行效果:

Traceback (most recent call last):

File "E:/Python33/python_workspace/test_fun.py", line 21, in

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來說,是可以使用這樣的方式進行賦值

如:

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

運行效果:

[1, 2, 3],2,hongten,()

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.