10. Advanced function

Dynamic parameters in formal parameters

def func(a,b,*args,c='f',**kwargs):
    print(a)
    print(b)
    print(args)
    print(c)
    print(kwargs)
func ( 9,2,3,4,45,6, c = ' 3 ' , d = 45, f = ' pp ' )
 # 9 
 2 
 ( 3, 4, 45, 6 )
  3 
 { ' d ' : 45, ' f ' : ' pp ' }

 

args is to put the redundant positional parameters in the actual parameters into a tuple     

kwargs is to put the redundant keyword parameters in the actual parameters into a dictionary

Argument order of final parameters: positional parameters, *args, default parameters, **kwargs

* When the function call is executed, the input parameter is an iterable object, and the element meaning can be added to args

** When the function call is executed, all the key-value pairs of the dictionary can be put into a dictionary for kwargs (the keys of the dictionary in this way must be strings)

 

def func(*args,**kwarg):
    print(args)
    print(kwarg)
dic1 = {2:'dsd','4':"dfaf"}
dic2 = {'3':'rerre','5':'vxcvxvcx'}
func(*[2,3,4,4,5],*dic1,**dic2)
#(2, 3, 4, 4, 5, 2, '4')
   {'3': 'rerre', '5': 'vxcvxvcx'}

 

There are three types of namespaces:

  global namespace

  local namespace

  built-in namespace

*The built-in namespace stores the names provided by the python interpreter: input, print, str, list, tuple... They are all familiar methods that we can use when we take them.

Loading and value order between the three namespaces:

Loading order: built-in namespace (loaded before program running) -> global namespace (program running: loaded from top to bottom) -> local namespace (program running: loaded when called)

Value order: value cannot be reversed

  Called locally: local namespace -> global namespace -> built-in namespace

  Called globally: global namespace -> built-in namespace

To sum up, when looking for variables, look for them from a small range, layer by layer to a large range.

scope

The scope is the scope, which can be divided into global scope and local scope according to the effective scope.

全局作用域:包含内置名称空间、全局名称空间,在整个文件的任意位置都能被引用、全局有效

局部作用域:局部名称空间,只能在局部范围生效

globals()   locals()  的用法

a = 2
b = 3
def func():
    c = 4
    d = 5
    print(globals())
    print(locals())
func()
#{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000020251399588>, '__spec__': None, 
'__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'H:/pycharm文件/day10/课堂练习.py', '__cached__': None, 'a': 2, 'b': 3, 'func': <function func at 0x000002024F501E18>} {'d': 5, 'c': 4} 将变量和对应的值用字典表示出来

  

global  在局部变量中声明一个全局变量  并且改变全局变量

nonlocal   在函数嵌套中通过在局部作用域中,对父级作用域(或者更外层作用域非全局作用域)的变量进行引用和修改,并且引用的哪层,从那层及以下此变量全部发生改变。

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324975379&siteId=291194637