Python functions (2): advanced functions and advanced python Functions

Source: Internet
Author: User
Tags variable scope

Python functions (2): advanced functions and advanced python Functions

Yesterday we talked about some basic definitions of functions. Today we will continue to study functions. Today we are mainly studying the namespace, scope, nature, and closure of functions.

Preview:

1. Write a function, pass in the modified file name, and the content to be modified. Execute the function to complete batch modification of the entire file. 2. Write a function, check whether each element of the input object (string, list, And tuples) contains null content. 3. Write a function and check the length of each value in the input dictionary. If the value is greater than 2, only the content of the first two lengths is retained and the new content is returned to the caller. Dic = {"k1": "v1v1", "k2": [,]} PS: the value in the dictionary can only be a string or a list.
Pre-Exercise

 

I. namespace

The essence of a namespace: the binding relationship between names and values

Namespace

Local namespace

Global namespace

Built-in namespace

*Built-in namespaceThe python interpreter provides the following names: input, print, str, list, And tuple... they are all familiar to us.

The loading and value order between the three namespaces:

Loading sequence:Built-in namespace (loading before running the program)-> global namespace (running: loading from top to bottom)-> local namespace (running: loading only when called)

Valid value:

In a local call: local namespace> global namespace> built-in namespace

x = 1def f(x):    print(x)print(10)
Use variable values locally

In global call: global namespace-> built-in namespace

x = 1def f(x):    print(x)f(10)print(x)
Reference variable x globally
print(max)
Built-in max in global reference

 

II. Scope

Why is there a concept of scope:

To ensure that the variables in the function do not affect the global

Scope is the scope of action, which can be divided into global scope and local scope according to the effective scope.

Global scope:Including the built-in namespace and global namespace, which can be referenced and globally valid anywhere in the entire file

Local scope:The local namespace can only take effect within the local range

The variables defined in the subroutine are called local variables, and the variables defined at the beginning of the program are called global variables.

The global variable scope is the whole program, and the local variable scope is the subroutine that defines the variable.

When a global variable has the same name as a local variable, the local variable takes effect in the subroutine that defines the local variable, and the global variable takes effect elsewhere.

Scope:

A small scope can be used, but a large scope cannot be used.

Range from large to small (figure)

In a small scope, if a variable is used, it is available in the current small scope. If it is not used in a small scope, it will be used in the upper level. If it is not used in the upper level, it will be used in the upper level, and so on. If none, an error is returned.

Globals and locals Methods

A = 20b = 50def func (): x = 1 y = 2 print (globals () # name in global scope print (locals () # name in local scope func () print (globals () # name print (locals () in the global scope # global or local
Globals and locals

Global keyword

A = 10def func (): a = 20def func1 (): global a # change the global variable a = 20 print (a) func () print (a) func1 () print ()
Global keyword

 

3. Function nesting and scope chain

Nested function call

def max2(x,y):    m  = x if x>y else y    return mdef max4(a,b,c,d):    res1 = max2(a,b)    res2 = max2(res1,c)    res3 = max2(res2,d)    return res3max4(23,-7,31,11)
Nested function call

Nested Function Definition

def f1():    print("in f1")    def f2():        print("in f2")    f2()f1()
Nested Function Definition (1)
def f1():    def f2():        def f3():            print("in f3")        print("in f2")        f3()    print("in f1")    f2()    f1()
Nested Function Definition (2)

Function scope chain

def f1():    a = 1    def f2():        print(a)    f2()f1()
Scope chain (1)
def f1():    a = 1    def f2():        def f3():            print(a)        f3()    f2()f1()
Scope chain (2)
def f1():    a = 1    def f2():        a = 2    f2()    print('a in f1 : ',a)f1()
Scope chain (III)

Nolocal keyword

1. This variable must be available externally.

2. A variable with the same name cannot appear before the internal function declares the nonlocal variable.

3. Modify the variable internally if you want to take effect in the first-level function with this variable externally.

 

def f():    a = 3    def f1():        a = 1        def f2():            nonlocal a             a = 2        f2()        print('a in f1 : ', a)    f1()    print('a in f : ',a)f()
Nolocal keyword

 

 

Iv. essence of function names

The function name is essentially the memory address of the function.

1. can be referenced

def func():    print('in func')f = funcprint(f)
Function referenced

2. elements that can be used as container types

Def f1 (): print ('f1 ') def f2 (): print ('F2') def f3 (): print ('f3') l = [f1, f2, f3] d = {'f1 ': f1, 'F2': f2, 'f3': f3} # Call l [0] () d ['F2'] ()
Functions are treated as easy-to-type elements.

3. It can be used as a function parameter and return value.

def func():    print('func')def func2(f):     f() func2(func)
Function Parameters
def func():    def func2():        print('hello')    return func2f2 = func()f2()f = func
Function return value

The first-class object refers

1. It can be created at runtime.

2. It can be used as a function parameter or return value.

3. objects that can be stored in variables.

Remember one sentence if you don't understand it.

 

5. Closure

Closure functions:Internal functions include references to variables in the external scope. Internal functions include references to the names of external scopes rather than full-drama scopes. This internal function is called a closure function.
# An internal function is called an internal function.

Closure

1. Close internal functions

2. The package contains references to variables in the external function scope.

def func():    name = 'eva'    def inner():        print(name)

 

def func():    name = 'eva'    def inner():        print(name)    return innerf = func()f()
Common Methods of closure Functions

Method _ closure _ for judging closure Functions __

# The output _ closure _ has a cell element: the closure function def func (): name = 'eva 'def inner (): print (name) print (inner. _ closure _) return innerf = func () f () # output _ closure _ is None: not the closure function name = 'egon' def func2 (): def inner (): print (name) print (inner. _ closure _) return innerf2 = func2 () f2 ()
Judgment of closure Functions
def wrapper():    money = 1000    def func():        name = 'eva'        def inner():            print(name,money)        return inner    return funcf = wrapper()i = f()i()
Nested Closure
from urllib.request import urlopendef index():    url = "http://www.cnblogs.com/liluning/"    def get():        return urlopen(url).read()    return getcnblogs = index()content = cnblogs()print(content)
Use closure functions to obtain network applications

 

Summary:

 

Preview answer 

Import osdef file_l (demo, I, j): ''' the user passes in the modified file name, and the content to be modified, executes the function, and completes batch modification of the entire file: param demo: input File: param I: string to be modified: param j: string to be changed: return: returns the source file and the modified file handle ''' with open (demo, 'R', encoding = 'utf-8') as read_f, \ open ("demo1.py", 'w', encoding = 'utf-8') as write_f: for line in read_f: write_f.write (line. replace (I, j) return read_f, write_ffile_l1, file_l2 = file_l ("demo. py "," def "," hahaha ") OS. remove (file_l 1. name) OS. rename (file_l2.name, file_l1.name) def space_l (str): ''' check whether each element of the object (string, list, And tuples) imported by the user contains null content.: Param str: Incoming data: return: Boolean value ''' for I in str: if I. isspace (): return False return Truemsg = "hello world! "Print (space_l (msg) def length (dic): ''' check the length of each value in the input dictionary. If it is greater than 2, only the content of the first two lengths is retained, and return the new content to the caller.: Param dic: return: ''' for I in dic: if len (dic [I])> 2: dic [I] = dic [I] [0: 2] return dicdic = {"k1": "v1v1", "k2": [11,22, 33,44]} length (dic) print (dic)
Preview answer

 

TIPS:

# Ternary computation # a = 20 # B = 10 # if a> B: # c = 5 # else: # c = 10 # if condition result if condition else condition Result # a = 20 # B = 10 # c = 5 if a> B else 10 # print (c)
Ternary Computation

Extracurricular entertainment:

>>> import thisThe Zen of Python, by Tim PetersBeautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.Flat is better than nested.Sparse is better than dense.Readability counts.Special cases aren't special enough to break the rules.Although practicality beats purity.Errors should never pass silently.Unless explicitly silenced.In the face of ambiguity, refuse the temptation to guess.There should be one-- and preferably only one --obvious way to do it.Although that way may not be obvious at first unless you're Dutch.Now is better than never.Although never is often better than *right* now.If the implementation is hard to explain, it's a bad idea.If the implementation is easy to explain, it may be a good idea.Namespaces are one honking great idea -- let's do more of those!
Zen of python

As mentioned in the Zen of python, namespace is a wonderful concept. Let's make full use of it!

 

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.