Small turtle talk 21 built-in functions and closures reflect summary

Classroom Summary:
Here are two examples:

x=5 
def fun1():
    x*=x
    return x

fun1()

This is being given, because the global variable is x = 5, and x is a local variable fun1, corresponding to the relationship between inner and outer layers, the inner layer can not obtain data of the outer layer. At this point want to reference an external variable, you need to add global, global variable references. as follows:

x=5 
def fun1():
    global x
    x *=x
    print(x)

fun1()

The second example is the addition of an internal function (note not closures! External closure return value of a function, see the example below), which corresponds to the inner space of the closure layer applied, the inner case is quite inside layer 'global variables'. The same can not refer to its data

def fun1():
    x= 5
    def fun2():
        x *=x
        return x
    return fun2()
print(fun1())

There are two ways to modify this time, the first one is equal to x lists. The list will no longer stack them so that no overall global problem does not exist

def fun1():
    x= [5]
    def fun2():
        x[0] *=x[0]
        return x[0]
    return fun2()
print(fun1())

Or reference to nonlocal, pay attention! And gobal difference in the gobal applied to real global variables


def fun1():
    x= 5
    def fun2():
        nonlocal x
        x *=x
        return x
    return fun2()
print(fun1())

After-school title

5. How Will access funIn () do?

def funOut():  
	def funIn():  
	    print('宾果!你成功访问到我啦')  
	return funIn 
	#注意,这里return是返回的funOut,而不是funIn 

Since the anti-back function rather than value, so it should add two brackets, and the second function here and does not return a value, so do not print Direct Print

##关于是否print的情况顺便作对比:
def fun1():
    x= 5
    def fun2():
        nonlocal x
        x *=x
        return x
    return fun2
print(fun1()())


def funOut():  
	def funIn():  
	    print('宾果!你成功访问到我啦')  
	return funIn
funIn()()

从上面两个对比可已看出,首先,当最后的外包函数返回为一个函数,那么说明内函数为一闭包,此时要调用就必须要加俩括号。
而第一个闭包返回了一个值x,所以最后需要将其打印出来。
第二个闭包print了一个值,返回值为none,此时就只需要调用外包函数即可。
实际上就是内保函数是返回值还是打印值得问题

6. The following is an example of "closure", see you next visual print what? ,

def funX():  
	x = 5  
	def funY():  
	    nonlocal x  
	    x += 1  
	    return x  
	return funY  
	  
a = funX()  	
print(a())  
print(a())  
print(a())  


答案:6
7
8

Analysis: First, a function to return to see the outside, so a = funx () = funY. Then funY () = x return value. x has been defined as a global variable with respect to the external space, so each call, x 1 will be added, the data is not deleted, and the outer x = 5 will change. So every print time, x value will change plus one, and so is 6.7.8

Published 17 original articles · won praise 1 · views 353

Guess you like

Origin blog.csdn.net/cccccccaaaaaaaaa/article/details/105317293