Record my python learning process -Day10 Advanced functions

Function parameters Ⅱ

  • The third parameter: dynamic parameters

    Moving too divided into two parameters: dynamic receive position parameters: * args; keyword receiving dynamic parameters: ** kwargs

    • ** dynamic receive position parameters: * args **

      def msg(*args):
          print('你的信息为:', args)
      
      msg('name', 111, False, [1, 3, 4, 5])
      
      # 运行结果:你的信息为: ('name', 111, False, [1, 3, 4, 5])

      Explain the significance of the above parameters: First of all args, args parameter is an ordinary, but if you add one in the front args, then it has a special meaning: in python, in addition to the multiplication sign, he has a magic of. Args added, so that parameter settings, then the argument will form all participants parameter receiving position, placed in a tuple, and assign the tuple args parameter to play a magic effect here is * and not args, a can achieve just results, but we PEP8 specifications provide for the use of args, convention.

      • Exercise : Incoming Int function in a variable number of data type, function and calculate all the numbers and returns.
      # 传入函数中数量不定的int型数据,函数计算所有数的和并返回。
      def cont(*args):
          n = 0
          for i in args:
              n += i
          return n
      
      cont = cont(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
      print(cont)
      
      # 运行结果: 55
    • Dynamic receive keyword arguments: ****** kwargs

      There are arguments angle positional parameters and keyword parameters of two kinds, python Now that there are * args can accept all the positional parameters then certainly there is a parameter to accept all keyword arguments, then this is kwargs, this empathy is a magic usage, kwargs convention used as a parameter. Exemplified: ** kwargs, accept all key parameters and then convert it into a 'dictionary' kwargs assigned to this parameter.

      def func(**kwargs):
          print(kwargs)
      
      func(name='Dylan', age=18, sex='男')
      
      # 运行结果:{'name': 'Dylan', 'age': 18, 'sex': '男'}
    • Full dynamic parameter of the wording

      def fun(*args, **kwargs):
          print(args)
          print(kwargs)
      
      fun('周一', '周二', '周三', '周四', name='Dylan', age=18, sex='男')
      
      # 运行结果:
      # ('周一', '周二', '周三', '周四')
      # {'name': 'Dylan', 'age': 18, 'sex': '男'}

      If a parameter is set, dynamic parameter, then he can receive all the positional parameters and keyword arguments, which would greatly enhance the function of the expansion, for the next argument in the case of more parameters to solve the problems of correspondence .

  • *** The magic of usage **

    • Function and break into the polymerization.

      • polymerization

        When the function definition, what if I just define a parameter called: args, then this parameter can only accept one argument:

        def msg(args):
            print('你的信息为:', args)
        
        msg('name')
        
        # 运行结果:你的信息为: name

        If for a prefixed number * args can then receive a plurality of arguments, and returns a tuple (** kwargs is the same reason, the plurality of conversion parameters into a dictionary keyword returned)
        so that:
        When the function definition , ' the' play the role of polymerization.

      • Beaten

        s = 'Dylan'
        li = [1, 2, 3, 4]
        tu = ('Name = Dylan', 'age = 18', 'sex = 男')
        
        def func(*args):
            print(args)
        
        func(*s, *li, *tu)
        
        # 运行结果:('D', 'y', 'l', 'a', 'n', 1, 2, 3, 4, 'Name = Dylan', 'age = 18', 'sex = 男')

        When the function is executed, the argument is I (available iterative type) You are here preceded by the parameter * or **, equivalent to those arguments disassembled into constituent elements as a location of a parameter, and then passed or args kwargs.
        So: in the execution of the function, * or ** play is broken up role.

        dic1 = {'name': 'Dylan', 'age': 18, 'sex': '男'}
        dic2 = {'0': 11, '1': 22, '2': 33}
        
        def func(**kwargs):
            print(kwargs)
        
        func(**dic1, **dic2) #
        
        # 运行结果:{'name': 'Dylan', 'age': 18, 'sex': '男', '0': 11, '1': 22, '2': 33}
    • Function can handle the remaining outer elements.

      Such addition may be broken in the function, outside the polymerization, the function can also be flexible use:

      # 之前讲过的分别赋值
      a,b = (1,2)
      print(a, b) # 1 2
      # 其实还可以这么用:
      a,*b = (1, 2, 3, 4,)
      print(a, b) # 1 [2, 3, 4]
      *rest,a,b = range(5)
      print(rest, a, b) # [0, 1, 2] 3 4
      print([1, 2, *[3, 4, 5]]) # [1, 2, 3, 4, 5]

      One can understand, not much to say.

  • Parameter sequence

    Positional parameters must be in the front, namely: location parameter, the default parameters.
    Then the dynamic parameters * args, ** kwargs where to put it?
    Dynamic parameters
    args, certainly not in front of the location parameter, so my argument will not receive positional parameters of the specific arguments of:

    # 这样位置参数a,b 始终接收不到实参了,因为 *args全部接收完了
    def func(*args, a, b, sex='男'):
        print(args)
        print(a, b)
    
    func(1, 2, 3, 4, 5)
    
    # 运行结果:程序报错了

    Then the dynamic parameters must be in the position behind the argument, he can default parameters behind it?

    # 这样也不行,我的实参的第三个参数始终都会将sex覆盖掉,这样失去了默认参数的意义。
    def func(a, b, sex='男', *args, ):
        print(args)  # (4, 5)
        print(sex)  # 3
        print(a, b)  # 1 2
    
    func(1, 2, 3, 4, 5)

    * Args it must be in the intermediate position parameter Default parameters: location parameter, * args, the default parameters .

    # 直接报错:因为**kwargs是接受所有的关键字参数,如果你想改变默认参数sex,你永远也改变不了,因为它会先被**kwargs接受。
    def func(a,b,*args,**kwargs,sex='男',):
        print(args) # (4, 5)
        print(sex) # 3
        print(a,b) # 1 2
        print(kwargs)
    
    func(1, 2, 3, 4, 5, age=80, sex='666')

    Therefore, this cut-off: all the formal parameters for the sequence:
    position parameter, args, default parameters, * kwargs.

  • The fourth parameter of parameters: Keyword parameters only

    Keyword argument only is python3x update new features, his position should be placed after the * args, front kwargs (if kwargs), which is the default location parameters, it does not matter with the default parameters before and after the order, it only accepts the key word pass parameters:

    def func(a,b,*args,sex= '男',c,**kwargs,):
        print(a,b)
        print(sex)
        print(args)
        print(c)
        print(kwargs)
    
    func(1,2,3,4,5,6,7,sex='女',name='Alex',age=80,c='666')
    
    """
    输出结果:
    1 2
    女
    (3, 4, 5, 6, 7)
    666
    {'name': 'Alex', 'age': 80}
    """

    The key parameter is defined only from the name you can see that he can only pass parameters by keyword arguments, in fact, you can not set it as the default value of the default parameters and parameters must pass, do not pass on the error.

    So in the end all formal parameters of the order parameter angle is:
    ** location parameter, args, default parameters, keyword parameters only, * kwargs. **

Namespace and scope

  • Namespaces

    After the python interpreter starts executing, it will open up a space in memory, whenever it encounters a variable, put the variable relationship between the name and the value recorded, but when faced with the function definition, Interpreter just put the function name is read into memory, indicating that the function exists, as to the internal logic of variables and functions, the interpreter is not concerned about. that is just the beginning when the function is loaded in, nothing more, only when the function is called and time of the visit, the interpreter will open up space for internal variables according to the variables declared within a function. with the function completes, the function of the internal variables as a function of the space occupied will be emptied finished.

    We first recall that when Python code to run functions that encounter is how to do, from the beginning of the implementation of the Python interpreter after it opened in a space in memory, whenever it encounters a variable, put the variable names and values the relationship between the corresponding record, but when faced with the function definition, only symbolic interpreter will read the name of the function such as memory, were aware of the existence of this function, as a function of internal variables and logic, the interpreter does not care.

    Such as when to execute a function call, Python interpreter will then open up a memory function to store this inside, this time, there are only concerned about what variables function, and the function of the variables are stored in memory opened up new , the function of internal variables can only function in use, and will function as finished, all the contents of this memory will be cleared.

    We give this 'relationship store the name and value of' space has a name: namespace .

    Space "of the relationship between the variable name and value" Run the code in the beginning, to create a storage called global namespace ;

    Temporary space opened up in the run function is called in the local namespace , also known as temporary namespace .

    Now we know, py file, stored value and the relationship between the variables of a space called the global namespace, and when a function is executed, the temporary memory will open up a space for temporary storage of the relationship between variables and function of the value of, this is called a temporary name space, or local name space.

    In fact, there is a space called the python built-in namespace special variables stored in built-in namespace is some built-in functions, and so that is brought by the:: input, print, list, etc.

    to sum up:

    • Global namespace -> py us directly in the document, the variable declared outside the function belong to the global namespace

    • Local namespace -> variables declared in a function will be kept in the local namespace

    • Built-in namespace -> storage python interpreter provides us with the name, list, tuple, str, int these are built namespaces

      # 内置名称空间:python源码给你提供的一些内置的函数,print input
      # print(666)
      # python分为三个空间:
          # 内置名称空间(builtins.py)
          # 全局名称空间(当前py文件)
          # 局部名称空间(函数,函数执行时才开辟)
  • Loading order

    The so-called load order, that is, the three space loaded into memory in the order, that is, the order of the three spaces created in memory, you think they can be simultaneously create it? Certainly not, then who should post it? We stroke along it: After starting the python interpreter, even without creating any variable or function, there will be some functions can be used directly such as abs (-1), max (1,3 ) and so on, start the Python interpreter is when it has been imported into memory for our use, so it must be loaded first built-in namespace, and then began to execute files from the top down line by line, at this time if you encounter initialize a variable, it will create a global name space , these correspondence relationship storage into, and then met when function is executed in memory to open up a temporary space, loading function of the number of variables, and so on.
    So load order for the three space:
    the built-in namespace (beginning running program load) -> global namespace (program execution: from top to bottom loading) -> local namespace (program execution: when the call load) .

    # 加载顺序:
    # 内置名称空间 ---> 全局名称空间  ----> 局部名称空间(函数执行时)
    def func():
        pass
    func()
    a = 5
    print(666)
  • The value of the order

    The value of the order is a reference to a variable, a space where to start first reference. This has a crucial point: the beginning of the space from which the reference (note: only reference can not be changed on a layer of variable) variable. We illustrate, respectively:

    # 如果你在全局名称空间引用一个变量,先从全局名称空间引用,全局名称空间如果没有,才会向内置名称空间引用。
    input = 666
    print(input) # 666
    
    # 如果你在局部名称空间引用一个变量,先从局部名称空间引用,局部名称空间如果没有,才会向全局名称空间引用,全局名称空间在没有,就会向内置名称空间引用。
    input = 666
    print(input) # 666
    input = 666
    def func():
        input = 111
        print(input) # 111
    func()

    The following example is relatively clear

    # 取值顺序(就近原则) 单向不可逆
    # LEGB原则
    input = 'Dylan'
    
    def func():
        input = 'xiaoyu'
        print(input)    # xiaoyu
    
    func()
    
    # (从局部找时)局部名称空间  ---> 全局名称空间  --->  内置名称名称空间
    
    input = 'Dylan'
    def func():
        print(input)    # Dylan
    
    func()
    print(input)    # Dylan
    

    Therefore, the value of the order of loading space order is reversed, the value of the order to satisfy the principle of proximity, and range from small to large reference range gradually layer by layer.

  • Scope

    Scope is the scope, in accordance with the entry into force of the range of view into global scope and local scope

    • Global scope : includes built-namespace and global namespace anywhere in the entire file can be used (follow from top to bottom by ⾏ execution).

    • The local scope : can be used within the function.

    Using the domain namespace for:

    1. The global scope: global name space + built-namespace

    2. Use local domain as: local namespace

  • Built-in functions globals (), locals ()

    The two built-in functions are at the right place here say, however, they can directly reflect the content scope, helps us to understand the scope of scope.

    • globals (): Returns the global scope all variables in the form of a correspondence relationship dictionary.

    • () Locals: Returns the current scope correspondence relationship dictionary in the form of a variable.

    Here is a global scope, one is the current scope, have to make clear, then, we use code verification:

    # 在全局作用域下打印,则他们获取的都是全局作用域的所有的内容。
    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()

Higher-order functions (nested functions)

In fact, we saw no stranger to the nested term, before we talked nested list, nested list is a list of lists in there, there might list that list ...... So by definition, function the nest is a function, and function.

Want to play a nested understand the key points of the function: as long as meet the function name + () is called function is not invoked if there is no function, understand that even understand. Then we practice example:

# 例1:
def func1():
    print('in func1')   # 1
    print(3)    # 2
def func2():
    print('in func2')   # 4
    print(4)    # 5
func1()
print(1)    # 3
func2()
print(2)    # 6

# 例2:
def func1():
    print('in func1')   # 3
    print(3)    # 4
def func2():
    print('in func2')   # 2
    func1()
    print(4)    # 5
print(1)    # 1
func2()
print(2)    # 6
# 例3:
def fun2(): 
    print(2)    # 2
    def fun3(): 
        print(6)    # 4
    print(4)    # 3
    fun3() 
    print(8)    # 5
print(3)    # 1
fun2()
print(5)    # 6

Guess you like

Origin www.cnblogs.com/guanshou/p/12105201.html
Recommended