内嵌函数

函数的内嵌即在函数内部定义函数,在内部定义的函数所有的一切都在函数内部,外部无法调用,举例如下:

>>> def fun1():
    print("fun1()正在被调用。。。")
    def fun2():
      print("fun2()正在被调用。。。")
    fun2()


>>> fun1()
fun1()正在被调用。。。
fun2()正在被调用。。。
>>> fun2()  #fun2()是在fun1()函数内部创建的,因此在函数外部无法调用
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
fun2()
NameError: name 'fun2' is not defined

例1:

def outside():
  print('I am outside!')
  def inside():
    print('I am inside!')

inside()

这里的inside()是无法调用的,正确的方式如下

def outside():

  print('I am outside!')

  def inside():

    print('I am inside!')

  inside()

outside()

原文地址:https://www.cnblogs.com/themost/p/6358944.html