• 【Python】 - Python的内置函数isinstance()中的参数classinfo一共有多少种,可以判断多少种类型?


    一、参考来源

    python - List of classinfo Types - Stack Overflow

    大家在使用Python的内置函数isinstance()时,一定会疑惑——第二个参数classinfo除了常见的int、float、str、tuple、dict、list外,还有哪些?

    本文的代码源于上面的链接,主要是进行一个中文的整合和搬运,以及稍加地通俗化。

    二、打印classinfo的种类

    我们在一个Python环境中执行以下代码。

    print([t for t in __builtins__.__dict__.values() if isinstance(t, type)])

    可以得到。

    ['_frozen_importlib.BuiltinImporter'>, 'bool'>, 'memoryview'>, 'bytearray'>, 'bytes'>, 'classmethod'>, 'complex'>, 'dict'>, 'enumerate'>, 'filter'>, 'float'>, 'frozenset'>, 'property'>, 'int'>, 'list'>, 'map'>, 'object'>, 'range'>, 'reversed'>, 'set'>, 'slice'>, 'staticmethod'>, 'str'>, 'super'>, 'tuple'>, 'type'>, 'zip'>, 'BaseException'>, 'Exception'>, 'TypeError'>, 'StopAsyncIteration'>, 'StopIteration'>, 'GeneratorExit'>, 'SystemExit'>, 'KeyboardInterrupt'>, 'ImportError'>, 'ModuleNotFoundError'>, 'OSError'>, 'OSError'>, 'OSError'>, 'OSError'>, 'EOFError'>, 'RuntimeError'>, 'RecursionError'>, 'NotImplementedError'>, 'NameError'>, 'UnboundLocalError'>, 'AttributeError'>, 'SyntaxError'>, 'IndentationError'>, 'TabError'>, 'LookupError'>, 'IndexError'>, 'KeyError'>, 'ValueError'>, 'UnicodeError'>, 'UnicodeEncodeError'>, 'UnicodeDecodeError'>, 'UnicodeTranslateError'>, 'AssertionError'>, 'ArithmeticError'>, 'FloatingPointError'>, 'OverflowError'>, 'ZeroDivisionError'>, 'SystemError'>, 'ReferenceError'>, 'MemoryError'>, 'BufferError'>, 'Warning'>, 'UserWarning'>, 'DeprecationWarning'>, 'PendingDeprecationWarning'>, 'SyntaxWarning'>, 'RuntimeWarning'>, 'FutureWarning'>, 'ImportWarning'>, 'UnicodeWarning'>, 'BytesWarning'>, 'ResourceWarning'>, 'ConnectionError'>, 'BlockingIOError'>, 'BrokenPipeError'>, 'ChildProcessError'>, 'ConnectionAbortedError'>, 'ConnectionRefusedError'>, 'ConnectionResetError'>, 'FileExistsError'>, 'FileNotFoundError'>, 'IsADirectoryError'>, 'NotADirectoryError'>, 'InterruptedError'>, 'PermissionError'>, 'ProcessLookupError'>, 'TimeoutError'>]

    为了增强可读性,我们把原作者的代码改一下。

    1. type_list = [t for t in __builtins__.__dict__.values() if isinstance(t, type)]
    2. # print(type_list)
    3. # print(type(type_list))
    4. type_list1 = [print(str(i)) for i in type_list]
    5. print(type_list1)

    改动代码后的执行结果。

    1. BuiltinImporter
    2. bool
    3. memoryview
    4. bytearray
    5. bytes
    6. classmethod
    7. complex
    8. dict
    9. enumerate
    10. filter
    11. float
    12. frozenset
    13. property
    14. int
    15. list
    16. map
    17. object
    18. range
    19. reversed
    20. set
    21. slice
    22. staticmethod
    23. str
    24. super
    25. tuple
    26. type
    27. zip
    28. BaseException
    29. Exception
    30. TypeError
    31. StopAsyncIteration
    32. StopIteration
    33. GeneratorExit
    34. SystemExit
    35. KeyboardInterrupt
    36. ImportError
    37. ModuleNotFoundError
    38. OSError
    39. OSError
    40. OSError
    41. OSError
    42. EOFError
    43. RuntimeError
    44. RecursionError
    45. NotImplementedError
    46. NameError
    47. UnboundLocalError
    48. AttributeError
    49. SyntaxError
    50. IndentationError
    51. TabError
    52. LookupError
    53. IndexError
    54. KeyError
    55. ValueError
    56. UnicodeError
    57. UnicodeEncodeError
    58. UnicodeDecodeError
    59. UnicodeTranslateError
    60. AssertionError
    61. ArithmeticError
    62. FloatingPointError
    63. OverflowError
    64. ZeroDivisionError
    65. SystemError
    66. ReferenceError
    67. MemoryError
    68. BufferError
    69. Warning
    70. UserWarning
    71. DeprecationWarning
    72. PendingDeprecationWarning
    73. SyntaxWarning
    74. RuntimeWarning
    75. FutureWarning
    76. ImportWarning
    77. UnicodeWarning
    78. BytesWarning
    79. ResourceWarning
    80. ConnectionError
    81. BlockingIOError
    82. BrokenPipeError
    83. ChildProcessError
    84. ConnectionAbortedError
    85. ConnectionRefusedError
    86. ConnectionResetError
    87. FileExistsError
    88. FileNotFoundError
    89. IsADirectoryError
    90. NotADirectoryError
    91. InterruptedError
    92. PermissionError
    93. ProcessLookupError
    94. TimeoutError
    95. [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]

    三、代码解析

    我们打印【__builtins__】,可以发现它是一个模块,属于Python内置模块。

    接着打印【__builtins__.__dict__】 ,可以发现结果中包括了该模块的所有(Python内置)函数、(Python内置)类(Class)等信息。

    1. {'__name__': 'builtins',
    2. '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.",
    3. '__package__': '',
    4. '__loader__': _frozen_importlib.BuiltinImporter,
    5. '__spec__': ModuleSpec(name='builtins', loader='_frozen_importlib.BuiltinImporter'>),
    6. '__build_class__': <function __build_class__>,
    7. '__import__': '_pydev_bundle.pydev_import_hook.import_hook'>>,
    8. 'abs': <function abs(x, /)>,
    9. 'all': <function all(iterable, /)>,
    10. 'any': <function any(iterable, /)>,
    11. 'ascii': <function ascii(obj, /)>,
    12. 'bin': <function bin(number, /)>,
    13. 'breakpoint': <function breakpoint>,
    14. 'callable': <function callable(obj, /)>,
    15. 'chr': <function chr(i, /)>,
    16. 'compile': <function compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1, *, _feature_version=-1)>,
    17. 'delattr': <function delattr(obj, name, /)>,
    18. 'dir': <function dir>,
    19. 'divmod': <function divmod(x, y, /)>,
    20. 'eval': <function eval(source, globals=None, locals=None, /)>,
    21. 'exec': <function exec(source, globals=None, locals=None, /)>,
    22. 'format': <function format(value, format_spec='', /)>,
    23. 'getattr': <function getattr>,
    24. 'globals': <function globals()>,
    25. 'hasattr': <function hasattr(obj, name, /)>,
    26. 'hash': <function hash(obj, /)>,
    27. 'hex': <function hex(number, /)>,
    28. 'id': <function id(obj, /)>,
    29. 'input': <function input(prompt=None, /)>,
    30. 'isinstance': <function isinstance(obj, class_or_tuple, /)>,
    31. 'issubclass': <function issubclass(cls, class_or_tuple, /)>,
    32. 'iter': <function iter>,
    33. 'len': <function len(obj, /)>,
    34. 'locals': <function locals()>,
    35. 'max': <function max>,
    36. 'min': <function min>,
    37. 'next': <function next>,
    38. 'oct': <function oct(number, /)>,
    39. 'ord': <function ord(c, /)>,
    40. 'pow': <function pow(base, exp, mod=None)>,
    41. 'print': <function print>,
    42. 'repr': <function repr(obj, /)>,
    43. 'round': <function round(number, ndigits=None)>,
    44. 'setattr': <function setattr(obj, name, value, /)>,
    45. 'sorted': <function sorted(iterable, /, *, key=None, reverse=False)>,
    46. 'sum': <function sum(iterable, /, start=0)>,
    47. 'vars': <function vars>,
    48. 'None': None,
    49. 'Ellipsis': Ellipsis,
    50. 'NotImplemented': NotImplemented,
    51. 'False': False,
    52. 'True': True,
    53. 'bool': bool,
    54. 'memoryview': memoryview,
    55. 'bytearray': bytearray,
    56. 'bytes': bytes,
    57. 'classmethod': classmethod,
    58. 'complex': complex,
    59. 'dict': dict,
    60. 'enumerate': enumerate,
    61. 'filter': filter,
    62. 'float': float,
    63. 'frozenset': frozenset,
    64. 'property': property,
    65. 'int': int,
    66. 'list': list,
    67. 'map': map,
    68. 'object': object,
    69. 'range': range,
    70. 'reversed': reversed,
    71. 'set': set,
    72. 'slice': slice,
    73. 'staticmethod': staticmethod,
    74. 'str': str,
    75. 'super': super,
    76. 'tuple': tuple,
    77. 'type': type,
    78. 'zip': zip,
    79. '__debug__': True,
    80. 'BaseException': BaseException,
    81. 'Exception': Exception,
    82. 'TypeError': TypeError,
    83. 'StopAsyncIteration': StopAsyncIteration,
    84. 'StopIteration': StopIteration,
    85. 'GeneratorExit': GeneratorExit,
    86. 'SystemExit': SystemExit,
    87. 'KeyboardInterrupt': KeyboardInterrupt,
    88. 'ImportError': ImportError,
    89. 'ModuleNotFoundError': ModuleNotFoundError,
    90. 'OSError': OSError,
    91. 'EnvironmentError': OSError,
    92. 'IOError': OSError,
    93. 'WindowsError': OSError,
    94. 'EOFError': EOFError,
    95. 'RuntimeError': RuntimeError,
    96. 'RecursionError': RecursionError,
    97. 'NotImplementedError': NotImplementedError,
    98. 'NameError': NameError,
    99. 'UnboundLocalError': UnboundLocalError,
    100. 'AttributeError': AttributeError,
    101. 'SyntaxError': SyntaxError,
    102. 'IndentationError': IndentationError,
    103. 'TabError': TabError,
    104. 'LookupError': LookupError,
    105. 'IndexError': IndexError,
    106. 'KeyError': KeyError,
    107. 'ValueError': ValueError,
    108. 'UnicodeError': UnicodeError,
    109. 'UnicodeEncodeError': UnicodeEncodeError,
    110. 'UnicodeDecodeError': UnicodeDecodeError,
    111. 'UnicodeTranslateError': UnicodeTranslateError,
    112. 'AssertionError': AssertionError,
    113. 'ArithmeticError': ArithmeticError,
    114. 'FloatingPointError': FloatingPointError,
    115. 'OverflowError': OverflowError,
    116. 'ZeroDivisionError': ZeroDivisionError,
    117. 'SystemError': SystemError,
    118. 'ReferenceError': ReferenceError,
    119. 'MemoryError': MemoryError,
    120. 'BufferError': BufferError,
    121. 'Warning': Warning,
    122. 'UserWarning': UserWarning,
    123. 'DeprecationWarning': DeprecationWarning,
    124. 'PendingDeprecationWarning': PendingDeprecationWarning,
    125. 'SyntaxWarning': SyntaxWarning,
    126. 'RuntimeWarning': RuntimeWarning,
    127. 'FutureWarning': FutureWarning,
    128. 'ImportWarning': ImportWarning,
    129. 'UnicodeWarning': UnicodeWarning,
    130. 'BytesWarning': BytesWarning,
    131. 'ResourceWarning': ResourceWarning,
    132. 'ConnectionError': ConnectionError,
    133. 'BlockingIOError': BlockingIOError,
    134. 'BrokenPipeError': BrokenPipeError,
    135. 'ChildProcessError': ChildProcessError,
    136. 'ConnectionAbortedError': ConnectionAbortedError,
    137. 'ConnectionRefusedError': ConnectionRefusedError,
    138. 'ConnectionResetError': ConnectionResetError,
    139. 'FileExistsError': FileExistsError,
    140. 'FileNotFoundError': FileNotFoundError,
    141. 'IsADirectoryError': IsADirectoryError,
    142. 'NotADirectoryError': NotADirectoryError,
    143. 'InterruptedError': InterruptedError,
    144. 'PermissionError': PermissionError,
    145. 'ProcessLookupError': ProcessLookupError,
    146. 'TimeoutError': TimeoutError,
    147. 'open': <function io.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)>,
    148. 'copyright': Copyright (c) 2001-2020 Python Software Foundation.
    149. All Rights Reserved.
    150. Copyright (c) 2000 BeOpen.com.
    151. All Rights Reserved.
    152. Copyright (c) 1995-2001 Corporation for National Research Initiatives.
    153. All Rights Reserved.
    154. Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
    155. All Rights Reserved.,
    156. 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    157. for supporting Python development. See www.python.org for more information.,
    158. 'license': See https://www.python.org/psf/license/,
    159. 'help': Type help() for interactive help, or help(object) for help about object.,
    160. 'execfile': <function _pydev_imps._pydev_execfile.execfile(file, glob=None, loc=None)>,
    161. 'runfile': <function _pydev_bundle.pydev_umd.runfile(filename, args=None, wdir=None, is_module=False, global_vars=None)>,
    162. '__IPYTHON__': True,
    163. 'display': <function IPython.core.display_functions.display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, raw=False, clear=False, **kwargs)>,
    164. 'get_ipython': >}

    接着,为了过滤出class的类别type,我们可以用isinstance(t, type)判断t究竟是否为Python内置的class中的一种。

    注意:上面的classinfo=type,暗示了type其实也是一种类,这个类中包括classinfo能使用的所有,当然也包括它自己。

    另外,如果直接输出类class,就会导致有class前缀;比如print(int),得到的结果是;为了消除这个前缀,我们可以用类class的__name__属性;比如print(int.__name__),输出int。

    因此代码也可以改成下面的形式;最后输出和上面的一样。

    1. type_list = [t for t in __builtins__.__dict__.values() if isinstance(t, type)]
    2. # print(type_list)
    3. # print(type(type_list))
    4. type_list1 = [print(i.__name__) for i in type_list]
    5. print(type_list1)

    有些读者可能是刚刚入门python,其实上面的x for x in X是一种推导式。

  • 相关阅读:
    从零开始实现lmax-Disruptor队列(三)多线程消费者WorkerPool原理解析
    【浅学Java】Bean的作用域和生命周期
    二叉堆(基础)
    [论文笔记]GPT-1
    go语言并发实战——日志收集系统(七) etcd的介绍与简单使用
    9.项目细节调整
    0x23根据地址读取内存服务
    起重机笔记 - 进阶篇(编辑中...)
    毕业设计选题Java+springboot校园新闻资讯系统源码 开题 lw 调试
    【校招VIP】前端HTML考察之cavas、svg
  • 原文地址:https://blog.csdn.net/PSpiritV/article/details/126096739