python全栈开发中级班全程笔记(第二模块、第三章)第4节 :函数进阶

python全栈开发笔记第二模块

第三章4节:函数进阶

一、函数进阶

1、函数进阶--命名空间

  命名空间,又称名称空间,或名字空间,就是存放变量名的地方比如 n = 1 , 1是存在内存的,但n 这个名字和绑定关系就存储在命名空间

  *命名空间和作用域是有直接关系的,

   主要分三种:

    • locals : 是函数内的名称空间,包括局部变量和形参
    • globals : 全局变量,函数定义所在模块的名字空间
    • builtins:内置模块的名字空间
    • 不同变量的作用域不同,就是由这个变量或函数所在的命名空间决定的

  **作用域的范围

    • 全局变量:全局存活,全局有效
    • 局部变量:临时存活,局部有效
        • 查看作用域一般用 locals() 和 globls()方法

 

代码实现功能:
>>> n = 6
>>> locals()                #打印当前变量
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 

'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'n': 6} >>> globals() #打印全局变量 {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>,

'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'n': 6} >>> dir(__builtins__) #打印内置模块的所有变量(注意使用语法,要先dir下再2个下划线) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError',
'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError',
'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError',
'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', #发现报错的语法,还有内置函数等
'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError',
'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning',
'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True',
'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning',
'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__',
'__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr',
'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance',
'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord',
'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str',
'sum', 'super', 'tuple', 'type', 'vars', 'zip']

 

2、函数进阶--作用域的查找顺序(空间

 

例:
n = 10
def func():                   # 定义一个嵌套函数
    n = 20
    print("func:",n)          # 每层以函数名做记号

    def func1():
        n = 30
        print("func1",n)

        def func2():
            print("func2:",n)

        func2()                #发现内两层的结果一样,如果没有n = 30,会向上一层找到 n = 20 以此类推

    func1()                    #这就是查找变量名由内而外的顺序

func()

  **由此就存在一个查找小规则

  • LEGB: 是查找顺序的英文首字母缩写
  • L: locals(函数内的名字空间)
  • E: enclosing(相邻外部前套函数的名字空间)
  • G: globals(全局变量:函数所在模块的名字空间)
  • B: builtins(内置模块的名字空间)

3、函数进阶--闭包

  闭包。是一个使用概念,或者说是一个规则,没有专门的语和定义,   

举例说明:

 

def func():
    n = 15
    def func2():
        print("func2:",n)
    return func2             # 返回内存地址
s = func()                   # 执行后也会返回内存地址,而不是执行效果
print(s)                     # 此时,正常来说,函数已经执行完,内部变量已释放
s()                          # 现在我再看下s()*加括号表示会执行函数的运行程序,不加括号会打印内存地址
# 此时发现func2 的代码被执行 n 被打印,为什么函数执行完已经释放内存了,还能执行函数内的代码呢?
这种效果就叫闭包,返回内部函数的名称,而在外部也拿到了顶层函数,
一旦顶部函数(func())里有返回值,这个函数的内存就不会被释放、
在外部可以执行函数内的值,并且可以用内部函数作用域内所有的值,这个现象就叫闭包,
函数内套子函数,子函数被返回了,反回了内存地址,
在外边执行子函数的时候,子函数又引用了外层函数的变量,子函数与外部函数存在了互相引用的关系,这种引用关系就叫闭包

 

 

 

猜你喜欢

转载自www.cnblogs.com/guoyilong/p/10180326.html
今日推荐