zoukankan      html  css  js  c++  java
  • 函数—函数进阶(一)

                                                函数—函数进阶(一)

    • 函数—函数进阶—鸡汤

                    1、电影推荐—《荒野求生》

                    2、书籍推荐—《百年孤独》

    • 函数—函数进阶—命名空间

          名称空间又名name space, 顾名思义就是存放名字的地方,例如,若变量x=1,1存放于内存中,那名字x存放在哪里呢?名称空间正是存放名字x与1绑定关系的地方

    名称空间共3种,分别如下:

    1. locals: 是函数内的名称空间,包括局部变量和形参

    2. globals: 全局变量,函数定义所在模块的名字空间

    3. builtins: 内置模块的名字空间

    1 #命名空间 又名name space   存放变量名与变量值绑定关系的地方。
    2 x = 1
    3 print(globals() )       #结果为:{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000245FDA96128>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/Python/work/myFirstPro/第3章/29—函数—函数进阶—命名空间.py', '__cached__': None, 'x': 1}
    4 print(locals())         #结果为:{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000245FDA96128>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/Python/work/myFirstPro/第3章/29—函数—函数进阶—命名空间.py', '__cached__': None, 'x': 1}
    5 print(__builtins__)     #结果为:<module 'builtins' (built-in)>
    6 print(dir(__builtins__))#结果为:['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', 'breakpoint', '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']
    7 
    8 #小结:
    9 # 不同变量的作用域不同,就是由这个变量所在命名空间决定的

    作用域即范围

    1. 全局范围:全局存活,全局有效

    2. 局部范围:临时存活,局部有效

    查看作用域方法 globals(),locals()

     1 x = 1
     2 globals()
     3 {'__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.
    
    Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <bound method ImportHookManager.do_import of <module '_pydev_bundle.pydev_import_hook.import_hook'>>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'WindowsError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'MemoryError': <class 'MemoryError'>, 'BufferError': <class 'BufferError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-Z plus Return to exit, 'exit': Use exit() or Ctrl-Z plus Return to exit, 'copyright': Copyright (c) 2001-2018 Python Software Foundation.
     4 All Rights Reserved.
     5 Copyright (c) 2000 BeOpen.com.
     6 All Rights Reserved.
     7 Copyright (c) 1995-2001 Corporation for National Research Initiatives.
     8 All Rights Reserved.
     9 Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
    10 All Rights Reserved., 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    11     for supporting Python development.  See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object., 'execfile': <function execfile at 0x00000202BA0FF6A8>, 'runfile': <function runfile at 0x00000202BA168F28>, '_': None}, 'sys': <module 'sys' (built-in)>, 'x': 1}
    12 locals()
    13 {'__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.
    
    Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <bound method ImportHookManager.do_import of <module '_pydev_bundle.pydev_import_hook.import_hook'>>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'WindowsError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'MemoryError': <class 'MemoryError'>, 'BufferError': <class 'BufferError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-Z plus Return to exit, 'exit': Use exit() or Ctrl-Z plus Return to exit, 'copyright': Copyright (c) 2001-2018 Python Software Foundation.
    14 All Rights Reserved.
    15 Copyright (c) 2000 BeOpen.com.
    16 All Rights Reserved.
    17 Copyright (c) 1995-2001 Corporation for National Research Initiatives.
    18 All Rights Reserved.
    19 Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
    20 All Rights Reserved., 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    21     for supporting Python development.  See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object., 'execfile': <function execfile at 0x00000202BA0FF6A8>, 'runfile': <function runfile at 0x00000202BA168F28>, '_': None}, 'sys': <module 'sys' (built-in)>, 'x': 1}
    22 __builtins__
    23 {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.
    
    Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <bound method ImportHookManager.do_import of <module '_pydev_bundle.pydev_import_hook.import_hook'>>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'WindowsError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'MemoryError': <class 'MemoryError'>, 'BufferError': <class 'BufferError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-Z plus Return to exit, 'exit': Use exit() or Ctrl-Z plus Return to exit, 'copyright': Copyright (c) 2001-2018 Python Software Foundation.
    24 All Rights Reserved.
    25 Copyright (c) 2000 BeOpen.com.
    26 All Rights Reserved.
    27 Copyright (c) 1995-2001 Corporation for National Research Initiatives.
    28 All Rights Reserved.
    29 Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
    30 All Rights Reserved., 'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    31     for supporting Python development.  See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object., 'execfile': <function execfile at 0x00000202BA0FF6A8>, 'runfile': <function runfile at 0x00000202BA168F28>, '_': None}
    32 dir(__buildins__)
    33 Traceback (most recent call last):
    34   File "<input>", line 1, in <module>
    35 NameError: name '__buildins__' is not defined
    36 dir(__builtins__)
    37 ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
    • 函数—函数进阶—作用域的查找空间

     1 n = 10
     2 def func():
     3     n = 20
     4     print('func',n)
     5 
     6     def func2():
     7         n = 30
     8         print('func2',n)
     9 
    10         def func3():
    11              print("func3",n)
    12 
    13         func3()
    14     func2()
    15 func()
    16 
    17 # 结果为:
    18 # func 20
    19 # func2 30
    20 # func3 30
    21 
    22 #作用域的查找顺序(一层一层往上查找) LEGB:
    23 # L:locals 是函数内的名字空间,包括局部变量和形参
    24 # E:enclosing 外部嵌套函数的名字空间
    25 # G:globals 全局变量,函数定义所在模块的名字空间
    26 # B:builtins 内置模块的名字空间
    • 函数—函数进阶—闭包

    1. 闭包,即函数定义和函数表达式位于另一个函数的函数体内(嵌套函数)。
    2. 这些内部函数可以访问它们所在的外部函数中声明的所有局部变量、参数。
    3. 当其中一个这样的内部函数在包含它们的外部函数之外被调用时,就会形成闭包。
    4. 也就是说,内部函数会在外部函数返回后被执行。而当这个内部函数执行时,它仍然必需访问其外部函数的局部变量、参数以及其他内部函数。
    5. 这些局部变量、参数和函数声明(最初时)的值是外部函数返回时的值,但也会受到内部函数的影响。
     1 def func():
     2     n = 10
     3 
     4     def func2():
     5         print("func2:",n)
     6     return func2    #返回func2的内存地址
     7 
     8 f = func()
     9 print(f)         #结果为:<function func.<locals>.func2 at 0x000002F1B9F59730>
    10 f()              #结果为:func2: 10
    11 
    12 #按常理来讲,执行完func()函数后,func2()已经释放了,但是它返回了   func2: 10
    13 #在外部拿到了内部的函数,并且还可以使用内部函数的作用域里面的值
    14 
    15 #闭包的意义:返回的函数对象,不仅仅是一个函数对象,在该函数外还包裹了一层作用域,这使得,该函数无论在何处调用,优先使用自己外层包裹的作用域
    • 函数—函数进阶—装饰器(http://www.cnblogs.com/alex3714/articles/5765046.html) 

     1 user_status = False       #用户登录后,这个改为True
     2 
     3 def login():
     4     username1 = "alex"         #假装这是DB里存的用户信息
     5     password1 = "abc123"      #假装这是DB里存的用户信息
     6     global user_status
     7 
     8     if user_status == False:
     9          username = input("user:")
    10          password = input("password:")
    11 
    12          if username == username1 and password == password1:
    13              print("welcome login.....")
    14              user_status = True
    15          else:
    16              print("wrong username or password")
    17 
    18     else:
    19          print("用户已登录,验证通过...")
    20 
    21 def home():
    22      print("————首页————")
    23 
    24 def america():
    25     print("————欧美专区————")
    26     login()
    27 
    28 def japan():
    29     print("————日韩专区————")
    30 
    31 def henan():
    32     print("————河南专区————")
    33     login()
    34 
    35 home()
    36 henan()
    37 america()
    38 
    39 #问题:现在有很多模块需要加认证模块,这个代码虽然实现了功能,但是需要更改需要加认证的各个模块的代码,这直接违反了软件开发中的一个原则“开放-封闭”原则。
    40 # 简单来说,它规定已经实现的功能代码不允许被修改,但可以被扩展:
    41 # 封闭:已实现的功能代码块不应该被修改
    42 # 开放:对现有功能的扩展开放
    43 
    44 
    45 #写个认证方法,每次调用需要验证的功能时,直接把这个功能的函数名当做一个参数,传给验证模块。
    46 user_status = False       #用户登录后,这个改为True
    47 
    48 def login(func):
    49     username1 = "alex"         #假装这是DB里存的用户信息
    50     password1 = "abc123"      #假装这是DB里存的用户信息
    51     global user_status
    52 
    53     if user_status == False:
    54         username = input("user:")
    55         password = input("password:")
    56 
    57         if username == username1 and password == password1:
    58             print("welcome login.....")
    59             user_status = True
    60         else:
    61             print("wrong username or password")
    62     if user_status == True:
    63        func()
    64 
    65 def home():
    66     print("————首页————")
    67 
    68 def america():
    69     print("————欧美专区————")
    70 
    71 def japan():
    72     print("————日韩专区————")
    73 
    74 def henan():
    75     print("————河南专区————")
    76 
    77 login(america)       #america专区,需要验证,所以调用 login,把需要验证的功能 当做一个参数传给login
    78 login(henan)         #america专区,需要验证,所以调用 login,把需要验证的功能 当做一个参数传给login
    79 
    80 #问题:现在每个需要认证的模块,都必须调用你的login()方法,并把自己的函数名传给你,人家之前可不是这么调用的,如果有100个模块需要认证,那这100个模块都得更改调用方式,这么多模块肯定不止是一个人写的,让每个人再去修改调用方式才能加上认证。
    • 函数—函数进阶—装饰器流程分析

     1 user_status = False       #用户登录后,这个改为True
     2 
     3 def login(func):
     4     username1 = "alex"         #假装这是DB里存的用户信息
     5     password1 = "abc123"      #假装这是DB里存的用户信息
     6     global user_status
     7 
     8     if user_status == False:
     9         username = input("user:")
    10         password = input("password:")
    11 
    12         if username == username1 and password == password1:
    13             print("welcome login.....")
    14             user_status = True
    15         else:
    16             print("wrong username or password")
    17     if user_status == True:
    18        func()
    19 
    20 def home():
    21     print("————首页————")
    22 
    23 def america():
    24     print("————欧美专区————")
    25 
    26 def japan():
    27     print("————日韩专区————")
    28 
    29 def henan():
    30     print("————河南专区————")
    31 
    32 america = login(america)        #相当于把america这个函数替换了
    33 henan = login(henan)
    34 america()                       #那用户调用时依然写
    35 henan()
    36 #问题:还不等用户调用,america = login(america)就会先自己把america执行了,但是应该用户调用的时候 再执行才对。
     1 #继续优化
     2 user_status = False       #用户登录后,这个改为True
     3 def login(func):          #把要执行的模块从这里传进来
     4     def inner():          #再定义一层函数
     5         username1 = "alex"         #假装这是DB里存的用户信息
     6         password1 = "abc123"      #假装这是DB里存的用户信息
     7         global user_status
     8 
     9         if user_status == False:
    10             username = input("user:")
    11             password = input("password:")
    12 
    13             if username == username1 and password == password1:
    14                     print("welcome login.....")
    15                     user_status = True
    16             else:
    17                     print("wrong username or password")
    18         else:
    19             print("用户已登录,验证通过...")
    20         if user_status:
    21              func()          #  只要这里验证通过了,就调用相应功能
    22 
    23     return  inner          #用户调用login时,只会返回inner的内存地址,下次再调用时加上()才会执行inner函数
    24 
    25 def home():
    26     print("————首页————")
    27 
    28 def america():
    29     print("————欧美专区————")
    30 
    31 def japan():
    32     print("————日韩专区————")
    33 
    34 @login        #henan = login(henan)           #相当于把henan这个函数替换了
    35 def henan():
    36     print("————河南专区————")
    37 
    38 #print(henan)                #inner
    39 henan()       #inner()
    • 函数—函数进阶—装饰器带参数1

       1 user_status = False                  #用户登录后,这个改为True
       2 def login(func):                     #把要执行的模块从这里传进来
       3     def inner(*args,**kwargs):                     # 使用非固定参数
       4         username1 = "alex"         #假装这是DB里存的用户信息
       5         password1 = "abc123"      #假装这是DB里存的用户信息
       6         global user_status
       7 
       8         if user_status == False:
       9             username = input("user:")
      10             password = input("password:")
      11 
      12             if username == username1 and password == password1:
      13                     print("welcome login.....")
      14                     user_status = True
      15             else:
      16                     print("wrong username or password")
      17         else:
      18             print("用户已登录,验证通过...")
      19 
      20         if user_status:
      21              func(*args,*kwargs)          # 使用非固定参数   只要这里验证通过了,就调用相应功能
      22 
      23     return  inner          #用户调用login时,只会返回inner的内存地址,下次再调用时加上()才会执行inner函数
      24 
      25 def home():
      26     print("————首页————")
      27 
      28 def america():
      29     print("————欧美专区————")
      30 
      31 @login
      32 def japan():
      33     print("————日韩专区————")
      34 
      35 @login        #henan = login(henan)           #相当于把henan这个函数替换了
      36 def henan(style):
      37     print("————河南专区————",style)
      38 
      39 #henan = login(henan)           #相当于把henan这个函数替换了
      40 #print(henan)                #inner
      41 henan("3p")                #inner()
      42 
      43 japan()             #inner()

       

       

    • 函数—函数进阶—装饰器带参数2

       1 user_status = False  # 用户登录了,就把这个改成True
       2 
       3 def login(auth_type):              #再包括一层在外面
       4     def outer(func):                # 把要执行的模块从这里传进来
       5         def inner(*args, **kwargs):   # 使用非固定参数
       6             _username = "alex"          # 假装这是DB里存的用户信息
       7             _password = "abc!23"        # 假装这是DB里存的用户信息
       8             global user_status
       9             if user_status == False:
      10                 username = input("user:")
      11                 password = input("pasword:")
      12                 if username == _username and password == _password:
      13                     print("welcome login....")
      14                     user_status = True
      15                 else:
      16                     print("wrong username or password!")
      17             else:
      18                 print("用户已登录,验证通过...")
      19             if user_status == True:
      20                 func(*args,**kwargs) # 使用非固定参数,支持多个参数;
      21         return inner                       # 用户调用login时,只会返回inner的内存地址,下次再调用时加上()才会执行inner函数
      22     
      23     return outer
      24 def home():
      25     print("---首页----")
      26 def america():
      27     print("----欧美专区----")
      28 
      29 def japan():
      30     print("----日韩专区----")
      31 @login('QQ')      # henan = login('qq')(henan) = inner
      32 def henan(style):
      33     print("----河南专区----",style)
      34 
      35 henan("3p")          #传入了参数

     

  • 相关阅读:
    位运算技巧2
    如果函数的参数是一个指针,不要指望用该指针去申请动态内存
    位运算 技巧1
    野指针?空指针?
    面试题:位操作实现四则运算
    面试题:递归颠倒栈 与栈排序
    求一个数任意位的值及位数
    基数排序
    面试题:最长回文子串(即求对称字符串的最大长度 )
    数据结构之后缀数组suffix array
  • 原文地址:https://www.cnblogs.com/wqq0723/p/9612788.html
Copyright © 2011-2022 走看看