Function return value
Multiple return statements:
def guess(x): if x > 3: return "> 3" else: return "<= 3"
DEF showplus (X): Print (X) return X +. 1 return X + 2 # Results of 10 . 11 # After the first return from the results appear below will not be executed
DEF Fn (X): for I in Range (X): IF I>. 3 : return I the else : Print ( " {}. 3 IS Not Greater Within last " .format (X)) # Fn (. 5) performed structure 4 # the Fn (3) 3 IS not Greater Within last 3 # can see, we can control statements by controlling conditions return
to sum up:
- python function uses the return statement returns the "return value"
- All functions have a return value, if there is no return statement, an implicit call to return None
- The return statement is not necessarily the last statement in a function block
- There may be a function of multiple return statements, but only one can be executed without a return statement is executed, an implicit call to return None
- If necessary, you can show the call return None, can be abbreviated return
- If the function executes a return statement, the function will return, other current statement after the return statement is executed will not be executed
- Role: the end of the function call, the return value
Return multiple values:
- Function can not return multiple values simultaneously
- return [1,3,5] returns a list is specified, a list of objects
- return 1,3,5 seemingly return multiple values, the implicit python is encapsulated into a tuple
Deconstruction can be used to advance
def showlist(): return 1, 3, 5 x, y, z = showlist()
Nested functions
DEF Outer (): DEF Inner (): Print ( " Inner " ) Print ( " Outer " ) Inner () Outer () # Inner () # error, inner undefined. That there is scope function
- Function visible range, which is the concept of scope
- Internal functions can not be used directly on the outside, NameError will throw an exception, because it is not visible
Scope
- The visible range of an identifier, which is the scope identifier. General often said that the variable scope
For example, comparison of Case 1 and Case 2
# Case. 1 X =. 5 DEF foo (): Print (X) foo () # Executive structure, multiplexing the global variable X # Case 2 X =. 5 DEF foo (): X + =. 1 Print (X) foo () # error, x + = 1 both x = x + 1, where x is reassigned, all x = x + 1 where x is either no value
Global scope:
- Throughout the program execution environment is visible
The local scope:
- Visible internal function, etc.
- Local variables can not exceed the scope of its use in local scope
DEF Fn1 (): X =. 1 # local scope, within Fn1 DEF Fn2 (): Print (X) # invisible Print (X) # invisible
Examples scopes nested structure:
#例子1、 def outer1(): # o = 65 def inner(): print("inner {}".format(o)) print(chr(o)) print("outer {}".format(o)) inner() outer1() #例子2、 def outer2(): # o = 65 def inner(): o = 97 print("inner {}".format(o)) print(chr(o)) print("outer {}".format(o)) inner() outer2()
From the examples:
- Variable Scope outer visible inner scope
- Inner innermost scope, if the definition of o = 97, corresponding to the current scope to redefine a new variable o, but this does not cover the outer scope o the outer o
x= 6 def foo(): x += 1 foo()
Error:
- x + = 1 is equivalent to x = x +1
- X corresponds to the definition of a local variable inside foo, then foo inside all the local variable x is the x
- But x is not yet complete assignments, it was on the right used to do the operation plus 1
Solve the problem of global variables global, nonlocal to solve
Global Variables global
Case
# X =. 6 DEF foo (): Global X X = 10 X + =. 1 # is not being given, Print (X) # printing. 11 Print (X) # error, can not find the identifier b
- Use the keyword global variables, x statement within the foo defined for global action to use an external domain x
- However, x = 10 both defined assignment for a variable outside the scope of the assignment within the scope x, instead of defining a new variable in the innermost scope, all x + = 1 does not complain, pay attention: where x is still scope Global
global summary:
- x = 1 This is the cause of the error generated special form? After the first reference to the assignment, and dynamic languages python is considered the definition of assignment, in order to be referenced. Solution before this statement increases assignment statement x = 0 and the like, or the use of global tell internal scope, global scope to find the variable definitions
- X = 5 internal scopes such assignment will redefine the role of the local variables used in the domain x, however, once the scope using global statement x is global, then x = 5 is equivalent to the global scope the assignment variable x
global use principles:
- Outside the scope of the variable scope will be visible inside, but do not be used directly in the local scope of this internal, since the purpose of the function is to package, as far as possible from the outside world
- If the function requires the use of an external global variables, use the function parameter of mass participation to solve
- Bottom line: do not global. It is to learn in-depth understanding of variable scope
Closure
- Free variables: local variable is not defined in scope. Variables such as outside the scope of the definition of the function of the outer memory function
- Closure: is a concept appears in the nested function refers to the function of the inner layer free variables referenced function, to form a closure.
Case:
DEF counter (): c = [0] DEF INC. (): c [0] + = 1 # will complain it? return c [0] return INC. foo = counter () Print (foo (), foo ()) # print the results? c = 100 Print (foo ()) # print the results?
Code analysis:
- Not being given, c is already defined in the counter function, and use inc c is modified to element values rather than redefining the variables
- A first printing result is 1, 2
- The last line is printed result 3
- c, and counter the penultimate line in c different, but inc cited is a free variable formal counter variable c
- This is python2 the implementation of closures way, python3 can also use the nonlocal keyword
nonlocal keyword
Use the nonlocal keyword, the variable is marked as local scope is not defined, but the definition of the role of the local superior of one level domain, but can not be defined in global scope
example:
def counter1(): c = 0 def inc(): nonlocal c c += 1 return c return inc foo = counter() foo() foo()
- c is the local variables of the outer function, internal functions cited
- Internal functions use nonlocal keyword to declare the variable c is defined at a higher level of scope rather than local scope
Default value Scope
Case
Case #. 1
DEF foo (= xyz. 1 ): Print (xyz) foo () # printing. 1 foo () # printing. 1 Print (xyz) # error NameError current scope is not variable xyz # Case 2 DEF foo (xyz = [] ): xyz.append ( . 1 ) Print (XYZ) foo () # [. 1] foo () # [1,1]
In Case 2 Why the second foo () will print 2 1
- Because functions are objects, python change the default value of the function on the property, this attribute is the function object associated with the entire life cycle
- View foo .__ defaults__
Run the following cases
def foo(xyz=[], u='abc', z=123): xyz.append(1) return xyz print(foo(), id(foo)) print(foo.__defaults__) print(foo(), id(foo)) print(foo.__defaults__) #执行结果 [1] 139927086673704 ([1], 'abc', 123) [1, 1] 139927086673704 ([1, 1], 'abc', 123)
to sum up:
- Function address has not changed, that is not changed for this object, call it, its properties __defaults__ tuple stored defaults
- xyz The default value is a reference type, a reference element changes in types of changes, not the tuples
Run the following cases:
def foo(w, u='abc', *, z=123, zz=[456]): u = 'xyz' z = 789 zz.append(1) print(w, u, z, zz) print(foo.__defaults__) foo('magedu') print(foo.__kwdefaults__) 运行结果 ('abc',) magedu xyz 789 [456, 1] {'z': 123, 'zz': [456, 1]}
- All positions __defaults__ attribute parameters stored in the default value tuple
- Properties __kwdefaults__ dictionary used to save all keyword-only parameter default values
Case-demand changes:
For example, a list of cases to increase the problem if I do not want him to increase it?
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__)
- In vivo function, does not change the default value
- xyz is a copy of the incoming parameters or default values for the parameters, if wanted to modify the original parameters, powerless
The second 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__)
- Type Default immutable
- If you create a list using the default None
- If you pass a list, in-place modify this list
the first method
- Use shadow copy to create a new object, you can never change the parameters passed
The second method
- You can choose to create or modify the flexibility of the incoming object by determining the value of
- This method is flexible, widely used
- Many function definition, you can see the use None of this immutable value as the default parameter, we can say this is an idiom
Variable name resolution principle LEGB
- Local, local scope, local scope of the local namespace. Create a function call, the call ends demise
- Enclosing, Python2.2 nested function is introduced to realize the closure, the external function is nested namespace function
- Global, global scope, both a namespace for a module, import the module is created, the demise when the interpreter exits
- Namespace Build-in, built-in module, the life cycle is created when the python interpreter from start to die out when the interpreter exits. For example: print (open), print and open are built-in variables
- So the search order is LEGB
Function to destroy
Global Functions destruction
- Redefining the function of the same name
- del statement removes the function object
- When the program exits
def foo(xyz=[], u='abc', z=123): xyz.append(1) return xyz print(foo(), id(foo), foo.__defaults__) def foo(xyz=[], u='abc', z=123): xyz.append(1) return xyz print(foo(), id(foo), foo.__defaults__) del foo print(foo(), id(foo), foo.__defaults__)
Local destruction of functions
- Redefining the function of the same name in the parent scope
- del statement removes the function name, the function object reference count by 1
- When the parent scope destroyed
def foo(xyz=[], u='abc', z=123): xyz.append(1) def inner(a=10): pass print(inner) def inner(a=100): print(xyz) print(inner) return inner bar = foo() print(id(foo),id(bar), foo.__defaults__, bar.__defaults__) del bar print(id(foo),id(bar), foo.__defaults__, bar.__defaults__)