Basics of getting started with Python-ternary expressions, namespaces, scopes, function name essence, closures

Source: Internet
Author: User
Tags closure

1. Three-dimensional expression (Trinocular operation)
# 13-dollar expression (Trinocular operation method) # The format is: True if the result of the if decision condition else is false # In addition, three-dimensional expression is only suitable for the more concise conditions to determine, more complex decision suggestions do not write code in this way, because the comparison is difficult for others to understand. = Ten =ifelse B # who returns large          Print(Compare)
2. Namespaces (namespace)
# 2 Namespaces (namespace) # namespaces are the name and object of the impression, you can also understand the namespace as a dictionary, for example, when defining variables, the variable name is the corresponding dictionary key, and the subsequent assignment is the value of the dictionary, and then for example, the function is the same, the function name is the dictionary key, The function body is the value of the dictionary;# each namespace is independent and has no relationship, so a namespace cannot have duplicate names, but different namespaces can have duplicate names and have no effect.  # in Python, namespaces are divided into built-in spaces, global spaces, and three of local space.  #(1) The Python interpreter has its own built-in space, and the built-in function is loaded into memory when the interpreter starts, and any module can access it, storing functions and exceptions.  #(2) Each module has its own namespace, called the global namespace, which records the variables of the module, including functions, classes, other imported modules, module-level variables, and constants.  #(3) Each function has its own namespace, called the local namespace, which records the variables of the function, including the parameters of the function and locally defined variables. 
3. Namespace Lookup Order
#3 Namespace Lookup order#Suppose you look for the "s" variable in the current namespace. #(1) Local namespace: First in the local namespace, if there is no discovery to continue to the upper level of the global namespace lookup, if no further to the upper-level built-in namespace lookup, if no more Python will return an error. #(2) global namespace: First look in the global namespace, if no discovery continues to the upper-level built-in namespace lookup, if no more Python will return an error. #(3) built-in namespaces: Returns an error directly if the built-in namespace difference is not found. #1) Variables that call the global namespace within the local namespace:A = 10defmy ():Print(a)#can print out successfullymy ()#If this is the case, it cannot be called:A = 10defmy (): a+ = 1#for non-mutable types, you can view them in a local namespace, but you cannot modify them directly.     #error: Unboundlocalerror:local variable ' A ' referenced before assignment    Print(a)#can print out successfullymy ()#variables that call built-in namespaces in the global namespace:x = 10defMy (x):#x =    Print(x)#x =15My (15)Print(x)#x = 10, the global namespace only looks for x in the current or ancestor built-in namespace, does not go to the local namespace to find x
4. Scope
# 4 Scopes # Scope is the scope of action, according to the scope of effective can be divided into global scope and local scope two.  #(1) Global scope: contains built-in namespaces and global namespaces that can be referenced anywhere in the entire file and are globally valid.  #(2) Local scope: local namespace, only valid within local scope. 
The difference between 5.globals and locals
#5 The difference between Globals and locals#Globals Method#Globals always print the global namedefA ():Print(Globals ())#The output in the local namespace is the same as the output in the global namespaceA ()Print(Globals ())#Locals Method#output What, according to the location of the locals decision. deffunc (): a= 10b= 12Print(Locals ())#variable information for local namespaces when printing informationfunc ()Print(Locals ())#Print the same information as Globals#Global keyword#If you need to modify the value of a variable in the global namespace in the local namespace, you need to declare it with global before it, and the action after it will be valid for the global variable. a= 12deffunc ():GlobalA#Global Declaration of variable A, after which the operation will be valid for global variablesA = 25Print(a)#A = 25 is valid for global variablesfunc ()Print(a)#A =
6. Nesting and scoping of functions
#6 nested and scoped chains of functions#(1) nested calls to functionsdefMy_compare1 (A, B):#Order 1    returnAifA > BElseB#Order 8 #顺序10defMy_compare2 (A,B,C):#Order 2C1 = My_compare1 (A, B)#Order 7    returnMy_compare1 (C,C1)#Order 9a= 10#Order 3b = 20#Order 4c = 15#Order 5Print(My_compare2 (A,B,C))#Order 6 #顺序11 The return value of the print function#(2) nested definitions of functionsdefF1 ():#Order 1    Print('In F1')#Order 3    defF2 ():#Order 4        Print('In F2')#Order 6F2 ()#Order 5F1 ()#Order 2#(3) scope chain of functions# OnedefF1 (): a= 1defF2 ():deff3 ():Print(a)#the printed result is 1, because now F3 belongs to the sub-local namespace, there is a parent local namespace, and if the current sub-local domain name space is not present, the variable A is looked up until the built-in namespace. f3 () F2 () F1 ( )# BothdefF1 (): a= 1defF2 (): a= 2F2 ()Print('A in F1:'A#the variable A here is printed 1 because the print and F2 functions are named in the F1 function body, and a = 2 in the F2 function body is the sub-local space of the space in which print is located, so print a will not look down. F1 ()#(4) nonlocal keywords#nonlocal can only be used for local variables to find the local variables in the upper layer from the current function#A variable modification that declares the intrinsic function of nonlocal affects the local variable that is closest to the current functionA = 10defF1 (): a= 1defF2 (): a= 2deff3 (): Nonlocal a#after declaring a nonlocal variable, the subsequent operation on variable a will only affect the local variables of the previous layer. A = 2 + 1f3 ()Print('A in F2:', a) F2 ()Print('A in F1:', a) F1 ()Print(a)
7. The nature of function names
#7 nature of function names#The function name is essentially the memory address of the function.#(1) can be quoteddeffunc ():Print('Hello word!') Fun=Funcfun ()#after the function body is called by Fun () and Func (), the printed information is exactly the samefunc ()#(2) an element that can be used as a container classdefF1 ():Print('F1')defF2 ():Print('F2')deff3 ():Print('f3') L=[F1,f2,f3]d= {'F1': F1,'F2': F2,'f3': F3}#calledL[0] ()#Call the contents of the F1 function bodyd['F2']()#Call the contents of the F2 function body#(3) can be used as a function parameter or return value#when the parameterdeffunc1 ():Print('ABC')defFunc2 (func1): Func1 ()#Call the FUNC1 function    Print('def') Func2 (func1)#Pass the FUNC1 function name as a parameter to the FUNC2 function#when the return valuedeffunc1 ():Print('ABC')defFunc2 ():Print('def')    returnFunc1#returns the FUNC1 function name as an addressa= Func2 ()#Copy the memory address of the FUNC1 function to variable aA ()#Call the FUNC1 function
8. Closures
#8 packet closure function#closures (Closure) are short for lexical closures (Lexical Closure) and are functions that reference free variables. This quoted free variable will exist with this function.#, even if it has left the environment to create it. So, there is another argument that closures are entities that are composed of functions and their associated reference environment. (It seems pretty hard to understand)#for the above explanation, I summarize the closure in the context of the nested function, the intrinsic function calls the variables of the external function, and the variables of the external function always exist, let's take a look at the example below. deffunc (): a=0Print('output variables for external functions:', a)defF1 ():Print('internal function Output variables:', a)returnf1f=func () f ()#The first call prints out "variables for output external functions: 0" and "intrinsic function output variables: 0"F ()#The call will print out the "intrinsic function output variable: 0", including the subsequent calls, the result of the printing is this, does not appear above the case, this is one of the ways of closure#the method of judging closure function __closure__#the __closure__ of the output has a cell element: a closure functiondeffunc (): Name='Eva'    definner ():Print(name)Print(Inner.__closure__)#Print Result: (<cell at 0x00000221eb0a0b58:str object at 0x00000221eb8438f0>,)    returnInnerf=func () f ()#the output __closure__ is none: Not a closure functionName ='Egon'defFunc2 ():definner ():Print(name)Print(Inner.__closure__)#because there is no variable in the outer function body (local space), the result is printed: None    returnInnerf2=Func2 () f2 ( )

Basics of getting started with Python-ternary expressions, namespaces, scopes, function name essence, closures

Related Article

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.