python function part

python function

Function, also known as method, is a reusable and single function. Function improves the reuse rate of code and the modularization of application. Appropriate modularization will make the program easier to maintain,

  1. standard
    • Choose a professional tool,

    • The function name should be in lowercase in English as far as possible, and the naming should know the meaning according to the name, even if the function name is a little longer,

    • Note: each function or class should have a comment to mark its function, parameter and return value,

      #!/usr/bin/env python
      # -*- coding: utf-8 -*
      """PEP 8 The standard requires each py There must be these two lines in the document, indicating the interpreter and coding standard of the document"""
      
    • For module import, try to keep the standard library module at the top, the third-party library at the middle, and the custom module at the bottom

      import datetime
      
      import requests
      
      from . import mymoudle
      
  2. function
    1. Parameters of function
      def myfunc(*args,**kwargs) ->bool:
          """
          :function A demo function
          :params
          
          """
          pass
      
      

      *args is any number of location parameters. This is a tuple. The one starting with * must be the last location parameter

      **kwargs is any number of keyword parameters. This is a dictionary. The keyword parameter starting with * * must be the last keyword parameter

      # Like this, first is a positional parameter, and second must be a keyword parameter
      def func(first,*,senond):
      
    2. Function Annotations

      # Function annotations are not mandatory, but proper use of function annotations will make the code clearer and easier to read
      def func(first:str,second:list) -> bool:
      
    3. Closure, [an excellent answer]( python closure - Zhihu (zhihu.com))

      A closure is like a class, but it is more concise and efficient than a class

      Function: save the external operating environment and realize the decoration

      def counter():
          # This is a counter
          count = 0
          def accumulate():  # An accumulation function is defined in the function
              nonlocal count # nonlocal declares that this external variable can be changed within the current scope
              count += 1
              return count
          return accumulate
      c = counter()
      print(c())
      print(c())
      # 1
      # 2
      # Every time c is called, it will automatically increment the count, just like a class
      
    4. yield generator and coroutine

      • yield

        def items():
            for i in [0,1,2]:
                yield i
        case = items()
        print(next(case)) # 0
        print(next(case)) # 1 
        # Here, the running environment before saving is implemented without closures or classes. It will run once only when next(case) is called every time. It will run until the next yield and wait for the next call. According to this feature, a pipeline can be formed
        
      • yield from

        def items():
            yield from [0,1,2]
        # The total usage of yield from is the same as that of the items function above
        
      • .send()

        def items():
            for i in [0,1,2]:
                a = yield i
                print(a)
        case = items() 
        next(case) 		# 0
        case.send(100) 	# 100 directly modify the value of this yield. During the operation of the function, it can interrupt the function at any time and modify the attribute value of the function in real time. This feature is very powerful
        
      • generator

        It can be considered that a function with the yield keyword is a generator. The generator will only produce one element at a time and will not start generating the next element until the next element needs to be used

        Function: when there is a list of millions of elements, it is obviously unrealistic to read the list into memory at one time, which will cause huge memory consumption. Instead, this problem can be avoided by using a generator

        1. generator

          # Use derivation to generate a generator
          gen = (item for item in range(10)) 
          
          # Use the function to generate a generator
          def items():
              for i in range(10):
                  yield i
          gen = items()
          
        2. Some operations of generator

          • Slice of generator

            Due to the nature of the generator, ordinary list slicing operations cannot act on the generator

            from itertools import islice
            gen = (item for item in range(10))
            gen1 = islice(gen,1,5)
            print(gen1) # <itertools.islice object at 0x000002178A24BCC8>
            # After slicing, it is still a generator
            
          • Generator is a large class. In order not to disturb the rhythm, it will be added in the future

      • Synergetic process

        A coroutine is a thread in user mode

        The collaborative process has such characteristics that among multiple tasks opened at the same time, only one is executed at a time. Only when the current task is blocked, it will switch to the next task to continue to execute. This mechanism can realize the synchronization of multiple tasks, successfully avoid the complexity of using locks in threads, and simplify the development

        Supplement when marking is collated to concurrency

    5. Decorator

      Closures are the foundation of decorators,

      Function: expand the current function without changing the current function code

      • Ordinary decorator

        def out(func):
            def decorator(a,b):
                # This is the decorator function
                print('This is the function of the decorator '+str(a))
                result = func(a,b)  #The call is completed internally and the result appears
                return result       #Then return the result
            return decorator  		
        @out
        def test(a,b):
            return a+b
        print(test(2,3))
        # This is the function of the decorator 2
        # 5
        
      • Decorator with parameters (three-level nested function)

        def out(args):  #Here are the parameters of the decorator itself
            def decorator(func): #Here is the decorated function
                def inner(a):    #Here are the parameters of the decorated function
                    print('hello '+args)
                    return func(a)
                return inner
            return decorator
        @out( 'world' )
        def test(a):
            return a
        print(test(1))
        # hello world
        # 1
        
      • Class decorator

        class DecroratorClass:
            def __init__(self,Decoratored):
                self.dec = Decoratored
            def __call__(self, *args, **kwargs):
                dec = self.dec
                return dec
        @DecroatorClass
        def test(a,b):
            return a+b
        
    6. Anonymous function lambda

      # Anonymous function
      test1 = lambda x,y:x+y
      # Ordinary function
      def test2(x,y):
          return x+y
      result1 = test1(1,2)
      result2 = test2(1,2)
      # The functions of such functions are equal, but lambda is more concise and elegant. It is used for callback functions, such as:
      re = sorted(lis,key=lambda x: x+1) # Take the structure of adding one to each element in lis as the standard to sort the original data of lis
      
    7. Some magic methods - Metadata

      Pick a tomato without cooking. We can learn about tomato__ color__ = red,

      Everything can be regarded as an object. A class is an object, a function is an object, and a list is an object. Every string in the list is also an object. If it is an object, it has properties and behaviors (Methods)

      def func(*args,default='hello'):
          '''An empty function'''
          return 1
      
      print(func.__doc__) # Object's annotation information
      print(func.__hash__()) # The hash value of the object
      print(func.__str__()) # Readable information of the object
      print(func.__repr__()) # Professional information of the object
      print(func.__defaults__) # Object's default parameter information
      print(func.__name__) # Object name
      '''
      An empty function
      103906995230
      <function func at 0x00000183156EC1E0>
      <function func at 0x00000183156EC1E0>
      None
      func
      '''
      
    8. Other higher order functions

      • map(func,iterable)

        # Call the func function on each element in the iteratable object to return a generator
        lis = [1,2,34,5]
        for i in map(str,lis):
            print(i)
        '''
        1
        2
        34
        5
        
        '''
        
      • filter(func,iterable) filter

        # Call func function for each element in the iteratable object, return only the elements that return True after static func operation, and return a generator, just like the enhanced version of map function
        lis = [1,2,34,5]
        def is_odd_number(param):
            return param%2 == 1
        for i in filter(is_odd_number,lis):
            print(i)
        
      • reduce(function, sequence, initial=None)

        # The reduce function passes sequence[0] and initial into function, and then passes the result and sequence[1] into function until the result is obtained
        from functools import reduce
        
        lis = [1,2,34,5]
        def add(a,b):
            return a+b
        print(reduce(add,lis))
        # 42
        
      • sorted(iterable,key,reverse=False) is a powerful sorting function

        This is a built-in method. It will create a new list as the return value, and the original list has not changed.

        iterable any iteratable object, which can be string, list (must be of the same type), dictionary, tuple,

        reverse=True reverse order

        key=func accepts a function with only one parameter. It applies this function to each element in the list and sorts the results. The use of key makes the use of sorted() very flexible. For example, it is combined with from functools import partial,

        result = sorted(iterable,key=lambda param:param+1)
        

        key can even be a class,

Remaining problems

  1. Why can a for loop automatically loop?

The above summary is my personal understanding. If there is any inaccuracy, please correct it!

Originally, I wanted to write functions and classes together. Now it seems too naive. There are too many details about functions and I don't know how to describe them. The above introduction is just common methods and basic knowledge. I will have a deeper understanding in the follow-up and continue to supplement.

💃 Now it's 2021.6.10. This typera editor is a little dangerous. It reported an error when opening, and even deleted my local document directly. Fortunately, I've been doing version control. It's too dangerous. Backup is very important. Take a warning.

Keywords: Python

Added by shadow_blade47 on Tue, 01 Feb 2022 21:47:08 +0200