Python core technology and real - Seven | custom function

  We use the previous code is relatively simple script, but the actual work is not a function of the whole person wrote from scratch tail in order to block the heap. A standardized worth learning Python program, unless the code is a very small (about 10 lines 20 lines) should consist of many functions, such code was more modular and standardized .

  Basics functions not described in detail here, we have talked about some other content!

A multi-state

  We look at one such function

def fun(a,b):
    return a+b
print(fun(1,2))
print(fun('1','2'))

  After the run will find that the effect is not the same. Python regardless of the type of input data, but which specific code to judge to perform the same function can be used simultaneously in an int, str data types of operations. This behavior is called polymorphism . This is also a great difference Python and Java, C and so on. Note that this is a neutral characteristic, it does not matter slightly superior, but need to add type checking at the beginning of the data when necessary.

II. Nested

  Another major feature of the Python function is to support nested functions

DEF fun1 ():
     Print ( ' in fun1 ' )
     DEF fun2 ():     # fun2 is nested inside the fun1 
        Print ( ' in fun2 ' ) 
    fun2 () 

fun1 ()

  Here again fun1 defined within the fun2, when calling fun1, prints 'in fun1', then the internal fun1 call fun2, in print 'in fun2'. What good does it do this?

  Nested advantage

    1. nested function can ensure the privacy of the internal function. Function can only be called an internal or external access functions will not be exposed to the global scope. If the internal functions have some private data (user database, passwords, etc.) want to be exposed to the outside, you can be used nested functions. Which is encapsulated within a function to access an external function only

DEF connect_DB ():
     DEF get_DB_configuration (): 
        Host = '' 
        username = '' 
        password = '' 
        return Host, username, password 
    Conn = connertor.connect (get_DB_configuration ())    # where all user information is not exposed the 
    return Conn                                         # only returns a connection state

  get_DB_configuration here () can only be called within connect_DB function within the global is not called.

    2. The rational use of nested functions, can improve the efficiency of the program. For example, we want to calculate the factorial of a number, before calculating needs to determine the legality of passing parameters

def factorial(input):
    if not isinstance(input,int):
        raise Exception('input must be an integer.')
    if input < 0:
        raise Exception('input must be greater or equal to 0')

    def inner_factorial(input):
        if input <=1:
                return 1
        return input*inner_factorial(input-1)
    return inner_factorial(input)

print(factorial(3))

  Such nested function is executed only when we check the validity of data once, and if we do not nested of each recursive determination should be carried out once, it will reduce the operating efficiency of the program. The work will often encounter this situation, it is necessary to use a nested.

III. Functions Variable Scope

  Variable scope and function similar to other languages, if the variable inside a function, a local variable is only valid inside the function, once the function is finished, the local variable will be recovered, inaccessible.

  Correspondingly, the global variable is defined over the entire file hierarchy, for example, so

MAX = 10
MIN = 1
def fun():
    if MAX > MIN:
        print(MAX)
fun()

  But we can not change the value of variables, such as this will appear in the error function

MAX = 10
MIN = 1
def fun():
    MAX+=1
fun()
UnboundLocalError: local variable 'MAX' referenced before assignment
 

Because Python interpreter default variable inside the function as local variables, found that MAX is not declared, it will throw an exception when you call. What if we define a variable name and the name of the global variable in a function, like what will happen?

A = 123
def fun():
    A = 456
    print('in fun A:{}'.format(A))
print('before call fun A:{}'.format(A))
fun()
print('after call fun A:{}'.format(A))
before call fun A:123
in fun A:456
after call fun A:123
in conclusion

But still have to pay attention, in the first call to the function if the global variable is not a re-statement of the same name and its variables, it can not change its value again. While if changes are needed for this variable, we need to add the keyword Global.

A = 123
def fun():
    global A  
    print(A)
    A = 456
    print('in fun A:{}'.format(A))
print('before call fun A:{}'.format(A))
fun()
print('after call fun A:{}'.format(A))
before call fun A:123
123
in fun A:456
after call fun A:456
in conclusion

   Remember Remember , this method must be used with caution. Because once the function is called the variable's value will be changed. If what time do not need to be modified to values which call times, when you want to trace up quite troublesome.

  There is nested function, internal functions can access external variables but can not change its value. To change the value, then inside the function variable with the keyword nonlocal statement

DEF fun1 (): 
    X = ' local ' 
    DEF fun2 (): 
        nonlocal X   # must be declared at the beginning 
        Print ( ' before Change X: {} ' .format (X)) 
        X = ' Inside ' 
        Print ( ' After Change X: {} ' .format (X)) 
    fun2 () 
    Print ( ' After Call fun2 X: {} ' .format (X)) 
fun1 ()
before change x:local
after change x:inside
after call fun2 x:inside
in conclusion

 IV. Closures, closures, closure

  Closures (closure) is the most important content of this lesson has the right not to understand. Closures and nested similar, but here the external function returns a function rather than a specific value, the function returns typically impart a variable that can be invoked to continue later.

  For example, we want to calculate the n-th power of a number, use closures could write

DEF nth_power (exponent The):
     DEF exponnet_of (Base):
         return Base ** exponent The
     return exponnet_of   # return value is a function 
Square nth_power = (2)    # calculates the square of a number 
Cube nth_power = (. 3)      # calculates a number of cubic 
print (Square (. 3 ))
 Print (Cube (. 3))

  Here external function nth_power () function return value is exponnet_of (), after executing

square = nth_power(2)  
cube = nth_power(3)

  After the external parameter exponent function is an internal function will be exponnet_of () Remember, when we call after the program will be able to smooth output.

  So it seems, we can also write such a program

def nth_power_rewrite(base,exponnet):
    return base**exponnet

  In fact, it is also possible, but the use of closure can make the program become more concise and easy to read. For example, we need to calculate the square of the lot number, to become such a

不用闭包
res1 = nth_power_rewrite(1,2)
res2 = nth_power_rewrite(2,2)
res3 = nth_power_rewrite(3,2)
res4 = nth_power_rewrite(4,2)
#使用闭包
squre = nth_power(2)
res1 = square(1)
res2 = square(2)
res3 = square(3)
res4 = square(4)

  First of all it seems, are a few closures as a parameter in each function call, more concise.

  Secondly, similar to the previous nested function to open start to do some extra work, but when several calls this function, you can put extra work on the external function, it can reduce unnecessary due to multiple calls s expenses.

  Another point later speaks, closures are often used with decorator (decorator).

 

Guess you like

Origin www.cnblogs.com/yinsedeyinse/p/11200542.html