• Python3学习随笔00120220615查看所有关键字及内置变量/方法


    问题:使用Python3编程时,为了避免命名冲突,有必要查看所有的关键字(keyword)和内置函数/异常(builtin)。那么,如何查看呢?

    01 - 查看Python3中的所有关键字(keyword

    >>> help('keywords')
    
    Here is a list of the Python keywords.  Enter any keyword to get more help.
    
    False               def                 if                  raise
    None                del                 import              return
    True                elif                in                  try
    and                 else                is                  while
    as                  except              lambda              with
    assert              finally             nonlocal            yield
    break               for                 not                 
    class               from                or                  
    continue            global              pass                
    
    >>> 
    >>> # OR
    >>>
    >>> from pprint import pprint as pp
    >>> from keyword import kwlist, iskeyword
    >>> 
    >>> pp(kwlist)
    ['False',
     'None',
     'True',
     'and',
     'as',
     'assert',
     'break',
     'class',
     'continue',
     'def',
     'del',
     'elif',
     'else',
     'except',
     'finally',
     'for',
     'from',
     'global',
     'if',
     'import',
     'in',
     'is',
     'lambda',
     'nonlocal',
     'not',
     'or',
     'pass',
     'raise',
     'return',
     'try',
     'while',
     'with',
     'yield']
    >>> 
    >>> iskeyword('with')
    True
    >>> iskeyword('without')
    False
    >>> 

    02 - 查看Python3中的所有内置函数/异常(builtin)

    >>> from pprint import pprint as pp
    >>> pp(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',
     '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',
     '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']
    >>> 
    >>> type(ArithmeticError)
    <class 'type'>
    >>> type(__build_class__)
    <class 'builtin_function_or_method'>
    >>> type(abs)
    <class 'builtin_function_or_method'>
    >>> 

    如要获取__builtins__的帮助,可借助于help(). 例如:

    >>> help(__builtins__)
    
    Help on built-in module builtins:
    
    NAME
        builtins - Built-in functions, exceptions, and other objects.
    
    DESCRIPTION
        Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.
    .
    .
    .

    03 - 小结

    • 查看所有关键字(keyword):(1) help('keywords') (2) pprint.pprint(keyword.kwlist)
    • 查看所有内置函数/异常(builtin):pprint.pprint(dir(__builtins__))
  • 相关阅读:
    Python第二天 (数据类型,变量 )
    python第一天(安装运行python)
    Linux shell 整数运算 let [ ] (( )) expr以及 浮点数 bc用法(转)
    2018年3月大事件
    2018年2月大事件
    项目假设与制约因素
    调用微信红包接口,本地可以服务器不可以。 请求被中止: 未能创建 SSL/TLS 安全通道
    【转】AddMvcCore,AddControllers,AddControllersWithViews,AddRazorPages的区别
    sql server create table 给字段添加注释说明
    HttpContext.SignInAsync 失效(表面解决了问题,未深入到.net core 源码去找问题,记录一下,等有时间翻一下.net core 源码试试能不能找到根本原因)
  • 原文地址:https://www.cnblogs.com/idorax/p/16380712.html
Copyright © 2020-2023  润新知