函数嵌套定义

1.1

def outer():

  a = 1

  def  inner():

    print(a)

       a += 1

    print('inner ')

  inner()

outer()

内部函数可以使用外部函数的变量。

# python3

nonlocal

1.2 闭包:

嵌套的函数,内部函数调用外部函数的变量。

1.2.1

def outer():

  a = 1

  def inner():

    print(a)

  print(inner.__closure__)

  return inner

outer()

1.2.2 内部函数可以引用外部函数的变量

def outer():

  a = 1

  def inner():

    print(a)

  return inner

outer()

在函数的外部去使用内部的函数;

1.2.3闭包应用

from urllib.request import urlopen
def get_url():
url = 'http://www.baidu.com'
def get():
ret = urlopen(url).read().decode('utf8')
print(ret)
return get

get_func = get_url()
get_func()
 
 


 

posted @ 2020-01-26 11:30  salary_01  阅读(151)  评论(0)    收藏  举报