Python Fourth Week study notes (1)

Source: Internet
Author: User
Tags closure unpack variable scope

Function
    • The Python function does not have a return statement, and implicitly returns a value of None
    • A function is a callable object, callable ()
function parameters
    • Parameters that are passed in when arguments are called match the number of definitions (variable parameter exceptions)
    • Position parameters
      • def f (x, Y, z) call using F (1, 3, 5)
      • Incoming arguments in order of parameter definition
    • Keyword parameters
      • def f (x, Y, z) calls using F (x=1, y=3, z=5)
      • Use the name of the formal parameter to enter and exit the argument, and if the parameter name is used, then the order of the parameters can be different from the order of the definition
    • Pass the reference
      • Requires that the positional parameter be passed in before the keyword parameter, which is the position parameter
function parameter Default value
    • When defined, follow a value after the formal parameter
    • Role
      • The default value of a parameter can be assigned to a default value without a given parameter when sufficient arguments are not passed in
      • With very many parameters, it is not necessary for the user to enter all parameters each time, simplifying the function call
Variable parameters
    • A formal parameter can match any parameter

    • Using * Before the formal parameter indicates that the parameter is a mutable argument and can receive multiple arguments
    • Collect multiple arguments as a tuple

    • Variable parameters for keyword parameters

      • Use the * * symbol before the formal parameter to indicate that you can receive multiple keyword parameters
      • The collected argument names and values form a dictionary
    • Positional variable parameters and keyword variable parameters
    • Positional variable parameters use an asterisk before the formal parameter *
    • Keyword variadic use two asterisk * before formal parameter * *
    • Positional variable parameters and keyword mutable parameters can all collect several arguments, positional variable parameters are collected to form a tuple, and keyword variable parameter collection forms a Dict
    • When mixing parameters, the variable parameter is placed at the end of the parameter list, and the normal parameter needs to precede the parameter list, where the variable parameter needs to be preceded by the keyword variable
Keyword-only parameters
    • If after an asterisk parameter, or a positional variable parameter, the common parameter that appears is actually not the normal parameter, but the keyword-only parameter
def fn(*args, x):print(x)print(args)
def(**kwargs, x):print(x)print(kwargs)

Direct reporting of grammatical errors
Can be understood as Kwargs will intercept all the keyword parameters, even if you write x=5,x will never get this value, so syntax error

    • Another form of the keyword-only parameter
      def fn(*, x,y):print(x,y)fn(x=5,y=6)

      After the * number, the normal parameter becomes the keyword-only argument that must be given.

Variable parameter and parameter default values
def fn(*args, x=5):print(x)print(args)
Parameter rules
    • Parameter list parameter General order is, normal parameter, default parameter, variable position parameter, keyword-only parameter (can with default value), variable keyword parameter
Parametric deconstruction
    • When providing arguments to a function, you can use * or * *, before the collection type, to unpack the structure of the collection type and extract all the elements as arguments to the function.
    • Non-dictionary types use * solution to form positional parameters
    • Dictionary types Use the * * solution to form the keyword parameter
    • The number of elements to be extracted must match the requirements of the parameter, and also match the type of the parameter.

    • Parametric deconstruction and variable parameters
      • When providing arguments to a function, you can use * or * *, before the collection type, to unpack the structure of the collection type and extract all the elements as arguments to the function.
function return value and scope return value of the function
    • The Python function returns the return value using the return statement
    • All functions have a return value and, if there is no return statement, implicitly calls return None
    • The return statement is not necessarily the last statement of a function's statement block
    • A function can have multiple return statements, but only one can be executed. If no return statement is executed, an implicit call to return None
    • If necessary, you can display the call return None, which can be shortened to return
    • If the function executes the return statement, the function returns, and the other statements after the currently executed return statement are not executed.
    • Effect: End Function call, return value

    • Return multiple values
      • function cannot return multiple values at the same time
      • return [1, 3, 5] is the specified return a list, is a list object
      • Return 1, 3, 5 appears to return multiple values, implicitly encapsulated by Python as a tuple
        def showlist():return 1, 3, 5x, y, z = showlist() # 使用解构提取更为方便
function nesting
    • Another function is defined in one function
      • The function has a visible scope, which is the concept of scopes
      • An intrinsic function cannot be used externally, it throws a Nameerror exception because it is not visible
Scope
    • Global scope

      • Visible throughout the program's running environment
    • Local scope

      • Visible inside functions, classes, and so on
      • Local variables cannot be used beyond the local scope in which they reside
    • Outer variable scope visible within scope of the inner layer
    • In the inner scope inner, if o=97 is defined, it is equivalent to redefining a new variable o in the current scope, but this o does not overwrite the O in the outer scope outer

    • Global variables Globals
      #x = 5def foo():global xx = 10x += 1 # 报错吗?print(x) # 打印什么?print(x) #打印什么?
    • Using variables from the global keyword, declare the x within Foo to use the x defined in the outer global scope
    • However, an assignment of x = 10 is defined, in which the internal scope assigns a value to the variable x of an outer scope, not a new variable in the internal scope, so x+=1 does not give an error. Note that the scope of x here is still global

    • X+=1 is this the cause of the special form of error? After the reference is assigned, the Python dynamic language is assigned to the definition before it can be referenced. Workaround, add an assignment statement such as x=0 before this statement, or use global to tell the internal scope to find the variable definition
    • An internal scope uses an assignment statement such as X = 5 to redefine the variable x that is used by the local scope, but once the scope uses global declaration x to be globally, then x=5 is equivalent to assigning a value to the variable x for the global scope

    • Global usage Principles
      • An external scope variable is visible inside the scope, but not directly in the local scope of the inner domain, because the function is designed to be encapsulated and isolated from the outside world.
      • If the function requires the use of an external global variable, use the function's parameter-pass argument to resolve
      • Bottom line: Don't use global. Learning it is to understand the scope of variables in depth
Closures (Key Concepts)
    • Free variable: A variable that is not defined in the local scope. For example, a variable that defines the scope of an outer function outside the memory function
    • Closures: A concept that appears in nested functions, meaning that the inner layer function refers to the free variable of the outer function, and the closure is formed. Many languages have this concept, the most familiar is JavaScript
    • The use of global can be solved, but this is using the globals, not the closures
    • If you want to close a normal variable, you can use nonlocal in Python3
nonlocal keywords
    • The nonlocal keyword is used to mark a variable as not defined in the local scope, but defined in a level local scope of the ancestor, but not in the global scope
Scope of default values
    • The function is also an object, and Python places the default value of the function in the attribute, which accompanied with the entire life cycle of the function object

    • Property defaults uses tuples to save all positional parameter defaults, and it does not change because it is used in the function body
    • Use dictionary in property kwdefaults to save default values for all keyword-only parameters

    • This default value can be modified by using a mutable type as the default value
    • Sometimes this trait is good, sometimes this trait is bad, there are side effects

    • The first of these methods
      • Create a new object with a shadow copy and never change the parameters passed in
        def foo(xyz=[], u=‘abc‘, z=123):xyz = xyz[:] # 影子拷贝xyz.append(1)print(xyz)foo()print(foo.__defaults__)foo()print(foo.__defaults__)foo([10])print(foo.__defaults__)foo([10,5])print(foo.__defaults__)

function body without changing the default value
XYZ is a copy of an incoming parameter or default parameter, and if you want to modify the original parameter, you can do nothing

    • The second method of
      • You can choose to create or modify incoming objects flexibly by judging the value.
      • This approach is flexible and widely used
      • Many of the definitions of functions can be seen using the immutable value of None as the default parameter, it can be said that this is a customary method
def foo(xyz=None, u=‘abc‘, z=123):    if xyz is None:        xyz = []    xyz.append(1)    print(xyz)foo()print(foo.__defaults__)foo()print(foo.__defaults__)foo([10])print(foo.__defaults__)foo([10,5])print(foo.__defaults__)

Use immutable type default values
If you use the default value of None, create a list
If you pass in a list, modify the list

Variable name resolution principle LEGB
    • Local, native scope, local namespace of the domain scope. Function call is created, call ends extinct
    • A nested function is introduced in enclosing,python2.2, which implements the closure, which is the namespace of the outer function of the nested function.
    • Global scope, which is the namespace of a module. Created when the module is import and dies when the interpreter exits
    • Build-in, the namespace of the built-in module, the life cycle is created when the Python interpreter starts and dies when the interpreter exits. For example, print (open), print and open are built-in variables
    • So the search order for a noun is legb.

Destruction of functions
    • Global function destruction

      • Redefine function with the same name
      • Del statement Delete function object
      • At the end of the program
    • Local function destruction
      • Re-define a function with the same name in the parent scope
      • Del statement Delete function name, function object reference count minus 1
      • When the parent scope is destroyed
Recursive
    • A function that calls itself directly or indirectly is recursive.
    • Recursion requires boundary condition, recursive forward segment, recursive return segment
    • There must be a boundary condition for recursion.
    • Recursive progression when boundary conditions are not met
    • Recursive return when boundary conditions are met

    • Recursive requirements

      • Recursion must have the condition of the launch, recursive call must be executed to execute this exit condition. Recursive calls with no exit criteria are infinite calls
      • The depth of recursive calls should not be too deep
      • Python limits the depth of recursive calls to protect the interpreter
      • exceeds recursion depth limit, throws Recursionerror maxinum recursion depth exceeded exceeds maximum depth sys.getrecursionlimit ()
    • Recursive performance

      • The loop is slightly more complex, but as long as it is not a dead loop, it can be iterated multiple times until the result is calculated
      • Recursion has a depth limit, and if recursion is complicated, the function repeatedly presses the stack, and the memory quickly overflows.
    • Indirect recursion

      • The function itself is called through another function
      • However, it is very dangerous to make a cyclic recursive call, but it is often possible to do so in the case of complex code. To avoid the recurrence of this recursive invocation, use the code's specifications.
    • Summarize
      • Recursion is a very natural expression, which is in line with logical thinking
      • Recursive relative operation efficiency is low, each call function to open up the stack frame
      • Recursion has a depth limit, and if the recursive hierarchy is too deep and the function repeatedly presses the stack, the stack memory quickly overflows
      • If you have a finite number of recursion, you can use recursion, or use loops instead, the loop code is slightly more complicated, but as long as it's not a dead loop, you can iterate until the result is calculated.
      • The vast majority of recursion can be implemented using loops
      • Even if the recursive code is concise, but can not be used without recursion
anonymous functions
    • Building an anonymous function using a lambda expression
    • Format

      • Lambda parameter list: expression
    • Use the Lambda keyword to define anonymous functions
    • Parameter list does not require parentheses
    • The colon is used to split the argument list and the expression
    • No need to use return, the value of the expression is the anonymous function return value
    • A lambda expression (an anonymous function) can only be written on one line, which is called a single-line function

    • Use
      • Lambda expressions are often used to simplify code when higher-order function parameters are passed
[x for x in (lambda *args: map(lambda x: x+1, args))(*range(5))] [x for x in (lambda *args: map(lambda x: (x+1,args), args))(*range(5))]

Python Fourth Week study notes (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.