形參角度(一共四種,後兩種)python
動態參數(萬能參數)*函數
# 定義一個函數時,*全部的位置參數聚合到一個元組中 def func(*args): # *args這裏是一個元組 print(f"名門正派都有:{arg}") func("少林","武當","峨眉") # 名門正派都有:("少林","武當","峨眉") --------------------------------- # 定義一個函數時,**全部的關鍵字參數聚合到一個字典中 def func(**kwargs): # **kwargs這裏是一個字典 print(kwargs) func(name="陳",age=25,hobby="跑步") # {name:"陳",age:25,hobby:"跑步"} --------------------------------- # *和**可同時使用 def func(*args,**kwargs): print(args) # ('少林', '武當', '峨眉') print(kwargs) # {'name': '陳', 'age': 25, 'hobby': '跑步'} func("少林","武當","峨眉",name="陳",age=25,hobby="跑步")
動態參數*特殊用法ui
# 函數內*用法 def func(*args): # *args這裏是一個元組 print(args) lis1=["少林","武當","峨眉"] lis2=["極樂谷","魔教"] func(*lis1,*lis2) # ("少林","武當","峨眉","極樂谷","魔教") # 當函數的執行時,*iterable表明打散 --------------------------------- def func(**kwargs): # **kwargs這裏是一個字典 print(kwargs) dic1={name:"陳",age:25,hobby:"跑步"} dic2={name:"王",age:27,hobby:"遊戲"} func(**dic1,**dic2) # {name:"陳",age:25,hobby:"跑步",name:"王",age:27,hobby:"遊戲"} # **dict表明打散,此方式只能打散字典
#函數外*用法 a,b,*c=[1,2,3,4,5,6,7] print(a,b,c) # 1,2,[3,4,5,6,7] # 在函數外*用於處理剩餘元素,以列表的形式將剩餘元素整合在一塊兒
形參角度的最終順序code
def func(a,b,*args,sex="man",**kwargs):
僅限關鍵字參數(瞭解便可)遊戲
# 在形參中以位置參數形式存在關鍵字參數與**kwargs之間,可是實參必須使用關鍵詞方式傳參. def func(a,b,*args,sex="man",c,**kwargs): print(a,b,args,sex,c,kwargs) func(1,2,3,4,5,c=[6,7],name="陳",age=25) # 執行結果 : 1 2 (3, 4, 5) man [6, 7] {'name': '陳', 'age': 25}
內置函數 : globals,locals內存
globals() # 以字典的形式返回全局做用域全部的變量對應關係作用域
locals() # 以字典的形式返回當前做用域的變量的對應關係it
# 在全局做用域下打印,則他們獲取的都是全局做用域的全部的內容。 a = 2 b = 3 print(globals()) print(locals()) ''' {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001806E50C0B8>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/lnh.python/py project/teaching_show/day09~day15/function.py', '__cached__': None, 'a': 2, 'b': 3} ''' --------------------------------- # 在局部做用域中打印。 a = 2 b = 3 def foo(): c = 3 print(globals()) # 和上面同樣,仍是全局做用域的內容 print(locals()) # {'c': 3} foo()
# 實例1: def func1(): print('in func1') print(3) def func2(): print('in func2') print(4) func1() # in func1 3 print(1) # 1 func2() # in func2 4 print(2) # 2 --------------------------------- # 例2: def func1(): print('in func1') print(3) def func2(): print('in func2') func1() print(4) print(1) # 1 func2() # in func2 in func1 3 4 print(2) # 2 --------------------------------- # 例3: def fun2(): print(2) def fun3(): print(6) print(4) fun3() print(8) print(3) # 3 fun2() # 2 4 6 8 print(5) # 5