The advanced level of python basic learning day11 function

  1. Trap of default parameter (only for variable data type): if the default parameter uses variable type data, the default parameter is the same (id is the same) no matter how many times it is called. The variable data type of the default parameter is neither global nor local, and will not disappear after definition (the local naming space will disappear).

    def func(num,nums=[]):
        nums.append(num)
        return nums
    ret1 = func(1)
    print(ret)
    >>>[1]
    ret2 = fun(2)
    print(ret2)
    >>>[1,2]  #Include the first data.
    
    #Example:
    def func(a,list=[]):
        list.append(a)
        return list
    ret1 = func(10,)
    print(ret1)         #[10]
    print(func(20,[]))  #[20]  #Reenter parameters for list
    print(func(100))    #[10,100]
    print(ret1)         #[10,100]
    
  2. Trap of local scope: in a function, if a variable is defined, but it is referenced before the variable is defined, even if the global variable has the referenced variable, an error will still be reported.

    #Example 1:
    count = 1
    def func():
    	count += 1
        print(count)
    func()
    IndentationError: unindent does not match any outer indentation level
        
    #Example 2:
    count = 1
    def func():
        print(count)
    func()      #1
    
    #Example 3:
    count = 1
    def func():
    	print(count)
        count = 1
    func()
    UnboundLocalError: local variable 'count' referenced before assignment
    
  3. global nonlocal

    • Declare a global variable in the local scope.

      #1.
      num = 0
      def func():
          num = 1
      print(num)    #0
      
      #2.
      def func():
          global num
          num = 1
      print(num)  #It will be reported wrong.
      
      #3.
      def func():
          global num
          num = 1
      func()
      print(num)  #1
      
      #3.
      num = 0
      def func():
          global num
          num = 1
      func()    
      print(num)    #1
      
      
    • nonlocal: unable to operate global variables; mainly used to modify local variables of inner function and outer function.

      def func1():
      	count = 1
          def inner():
              nonlocal count
              count+=1
          inner()
      
  4. The application of function name

    • The function name refers to the memory address of the function

    • Function name + () can execute the function

      #Example 1:
      def func():
      	print(1)
      f1 = func
      f2 = f1
      f2()     #1
      
      #Example 2.
      def func1():
          print(1)
      def func2():
          print(2)
      func2 = func1
      func2()    #1
      
    • Function name can be an element of container class data type

      #Example 3:
      def func1():
          print(1)
      def func2():
          print(2)
      def func3():
          print(3)
      l1 = [func1,func2,func3]
      for i in l1:
          i()   #1 2 3
      
    • Function name can be used as parameter of function

      def func0(a):
          print(1)
      def func1(x):
          x()
      func1(func0)      #1   
      
    • The function name can be the return value of the function.

      def func1():
          print(1)
      def func2(x):
          return x
      ret = func2(func)
      ret()       #1
      
  5. Format output (after version 3.6):

    • Basic expression:
    ```python
    
    name = 'python'
    age = '18'
    msg = f'My name is{name},This year{age}'    #Add a character f before the quotation mark
    
    ```
    
    • Expression can be added:

      count = 2
      print(f'Final result:{count**2}')
      
      name = 'python'
      print(f'My name is{name.upper()}')
      
      
      dic = {'name':'python','age':'18'}
      msg = f'My name is{dic["name"]},This year{dic["age"]}'   #Pay attention to the use of double quotation marks and single quotation marks to avoid ambiguity.
      
      list = ['python','18']
      msg = f'My name is{list[0]},This year{list[1]}' 
      
      
    • You can combine functions:

      def sum1(a,b):
          return a+b
      print(f'The end result is{sum1(1,2)}')
      
    • Advantages: 1. More optimized structure. 2. It can be used in combination with expressions and functions. 3. Higher efficiency

  6. Iterator:

    • Iteratable objects:

      Object: everything in python is an object. Iteratable: a value that can be iterated.

      From a professional point of view, an object with an internal "iter" method is an iterative object. For example: str, list, tuple, dict, set, range, file handle, etc.

    • Gets all methods of an object and represents them as strings: dir()

      s1 = 'qwer'
      print(dir(s1))  #Please self testing.
      
    • Determine whether an object is an iterative object:

      s1 = 'qwer'
      print('__iter__' in dir(s1))  #True
      
    • Advantages of iteratable objects:

      1. The stored data can be displayed directly and intuitively.
      2. It has many methods and is easy to operate.
    • Advantages of iteratable objects:

      1. Memory.

      2. You can't go through the for loop directly (you can't take a value directly), and python will automatically convert it into an iterator (see below) and then carry out the for loop (use the next() method to take a value, see below).

        l1 = [1,2,3,4]
        for i in l1:
            print(i) #python automatically converts it to an iterator internally, and then does a for loop
        
    • Iterator:

      Definition of iterator: an object with internal methods of iterator and next is an iterator. For example: file handle.

    • Determine whether it is an iterator:

      with open ('1.txt',encoding='utf-8',mode='w') as f1:
          print('__iter__' in dir(f1) and '__next__' in dir(f1))
      
    • Iteratable objects can be converted to iterators:

      s1 = 'qwert'
      obj = iter(s1)
      #Or:
      s1.__iter__()
      print(obj)   #Please self test and return the memory address of an iterator
      
    • Value the iterator:

      s1 = 'qwert'
      obj = iter(s1)
      next(obj)   #The first element of string s1 will be taken out
      next(obj)   #Will return the second element of string s1
      #Or:
      obj.__next__()
      
    • Advantages of iterators:

      1. Save memory. The iterator takes up only one data space in memory, because every time the last data is retrieved, it will be released in memory. The iterator has an inert mechanism. next takes only one value, never more.

    • Disadvantages of iterators:

      1. You cannot view the data directly.

      2. It can only be taken all the way down.

      3. Slow speed.

    • Comparison of iteratable objects and iterators:

      • The iteratable object is a data set with more operation methods, more intuitionistic and less storage data (millions of data, 8G memory is affordable).
      • When we focus on flexible data processing and enough memory space, we can set the data as an iterative object.
      • The iterator is very memory saving, it can record the value location, and it can get the value by adding the next method in a loop, but it is not intuitive, and the operation method is a single data set.
      • When the amount of data is too large, you can choose to set the data as an iterator.
    • Use the while loop to simulate the for loop to take values for the iteratable objects: (please test yourself)

      l1 = [1,2,3,4,5,6,7,8]
      obj = iter(l1)
      while 1:
          try:     #try: exception handling
              print(next(obj))
          except StopIteration:
              break
      

Tags: Python encoding less

Posted on Mon, 23 Mar 2020 09:06:11 -0400 by lizard