如下所示:
# -*- coding:utf-8 -*-# Author: Evan Mi # 函數(shù) def func1(): print('in the func1') return 0 # 過(guò)程 def func2(): print('in the func2') """多個(gè)值用逗號(hào)分割后返回,會(huì)分裝到一個(gè)tuple中返回,接收的時(shí)候,如果使用一個(gè)變量接收,那么這個(gè)接收變量就是一個(gè)tuple類型的如果接收的時(shí)候也用逗號(hào)分割多個(gè)值來(lái)接收,那么可以分別對(duì)應(yīng)返回tuple中的每一個(gè)值""" def func3(): return 1, 'hello', ['alex', 'wupei'], {'name': 'alex'} x = func1()y = func2()z = func3() # 一個(gè)值接收,是一個(gè)tupleq, w, e, r = func3() # 用對(duì)應(yīng)個(gè)數(shù)的值接收,每個(gè)變量對(duì)應(yīng)tuple對(duì)應(yīng)位置的值print(x)print(y)print(z) print("center".center(100, '*'))print(q)print(w)print(e)print(r) print("center".center(100, '*')) # 定義一個(gè)方法 def test(x_arg, y_arg): print(x_arg) print(y_arg) test(1, 2) # 位置參數(shù)調(diào)用test(y_arg=3, x_arg=5) # 關(guān)鍵字參數(shù)調(diào)用,直接給形式參數(shù)賦值 def test1(x_arg, y_arg, z_arg): print(x_arg) print(y_arg) print(z_arg) # 關(guān)鍵字參數(shù)不能寫(xiě)到位置參數(shù)之前test1(1, z_arg=2, y_arg=3) # 默認(rèn)值參數(shù)def test2(x_arg, y_arg=2): print(x_arg) print(y_arg) print("center".center(100, '*'))test2(1)print("center".center(100, '*'))test2(1, 3)print("center".center(100, '*'))test2(y_arg=5, x_arg=8) """在*args 前面有參數(shù)(x, *args),那么(1,2,3,4,5)正確,(x=1,2,3,4,5)正確,(2,3,4,5,x=1)錯(cuò)誤,給x多次賦值了在*args 后面有參數(shù)(*args,x,y)那么x,y只能采用關(guān)鍵字賦值方式(1,2,3,4,5,x=6,y=8) """ def test3(*args): print(args) test3(1, 2, 3, 4, 5)test3(*[1, 2, 3, 4, 5])print("center".center(100, '*')) def test4(x_arg, *args): print(x_arg) print(args) test4(1, 2, 3, 4, 5) def test5(**kwargs): print(kwargs) print(kwargs['name']) test5(name='alex', age=8)test5(**{'name': 'Evan', 'age': 8}) def test6(*args, xx): print(args) print(xx) # **kwargs 必須在最后# def test7(**kwargs,xx=3): 這樣定義是錯(cuò)誤的 print("test6")# test6(1, 2, 3, 4, 5999, xx=4)"""*args 接收位置參數(shù),轉(zhuǎn)換為tuple**kwargs 接收關(guān)鍵字參數(shù),轉(zhuǎn)換為dict位置參數(shù)不能寫(xiě)在關(guān)鍵字參數(shù)的后面""" def tt(xx=1, *args, **kwargs): print(xx) print(args) print(kwargs) def ttt(xx, **kwargs): print(xx) print(kwargs) def tttt(*args, xx, **kwargs): print(args) print(xx) print(kwargs) # kwargs接收的關(guān)鍵字參數(shù)的名字不能和函數(shù)列表中已有的其他參數(shù)相同# tt(2, 3, 4, 5, name=100, age=199, xx=98)# 出現(xiàn)了xx,優(yōu)先賦值給參數(shù)列表中的xx,而不是在dict中加入關(guān)鍵字為xx的key-value對(duì)# ttt(x=99, y=99, xx=43) tttt(1,2,3,4,5,x=100,y=33,xx=8)以上這篇對(duì)python3 中方法各種參數(shù)和返回值詳解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林站長(zhǎng)站。
新聞熱點(diǎn)
疑難解答
圖片精選