python - List of classinfo Types - Stack Overflow
大家在使用Python的内置函数isinstance()时,一定会疑惑——第二个参数classinfo除了常见的int、float、str、tuple、dict、list外,还有哪些?
本文的代码源于上面的链接,主要是进行一个中文的整合和搬运,以及稍加地通俗化。
我们在一个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'>]
为了增强可读性,我们把原作者的代码改一下。
- type_list = [t for t in __builtins__.__dict__.values() if isinstance(t, type)]
- # print(type_list)
- # print(type(type_list))
- type_list1 = [print(str(i)) for i in type_list]
- print(type_list1)
改动代码后的执行结果。
- 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
- [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)等信息。
- {'__name__': 'builtins',
- '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.",
- '__package__': '',
- '__loader__': _frozen_importlib.BuiltinImporter,
- '__spec__': ModuleSpec(name='builtins', loader=
'_frozen_importlib.BuiltinImporter'>), - '__build_class__': <function __build_class__>,
- '__import__':
'_pydev_bundle.pydev_import_hook.import_hook'>>, - 'abs': <function abs(x, /)>,
- 'all': <function all(iterable, /)>,
- 'any': <function any(iterable, /)>,
- 'ascii': <function ascii(obj, /)>,
- 'bin': <function bin(number, /)>,
- 'breakpoint': <function breakpoint>,
- 'callable': <function callable(obj, /)>,
- 'chr': <function chr(i, /)>,
- 'compile': <function compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1, *, _feature_version=-1)>,
- 'delattr': <function delattr(obj, name, /)>,
- 'dir': <function dir>,
- 'divmod': <function divmod(x, y, /)>,
- 'eval': <function eval(source, globals=None, locals=None, /)>,
- 'exec': <function exec(source, globals=None, locals=None, /)>,
- 'format': <function format(value, format_spec='', /)>,
- 'getattr': <function getattr>,
- 'globals': <function globals()>,
- 'hasattr': <function hasattr(obj, name, /)>,
- 'hash': <function hash(obj, /)>,
- 'hex': <function hex(number, /)>,
- 'id': <function id(obj, /)>,
- 'input': <function input(prompt=None, /)>,
- 'isinstance': <function isinstance(obj, class_or_tuple, /)>,
- 'issubclass': <function issubclass(cls, class_or_tuple, /)>,
- 'iter': <function iter>,
- 'len': <function len(obj, /)>,
- 'locals': <function locals()>,
- 'max': <function max>,
- 'min': <function min>,
- 'next': <function next>,
- 'oct': <function oct(number, /)>,
- 'ord': <function ord(c, /)>,
- 'pow': <function pow(base, exp, mod=None)>,
- 'print': <function print>,
- 'repr': <function repr(obj, /)>,
- 'round': <function round(number, ndigits=None)>,
- 'setattr': <function setattr(obj, name, value, /)>,
- 'sorted': <function sorted(iterable, /, *, key=None, reverse=False)>,
- 'sum': <function sum(iterable, /, start=0)>,
- 'vars': <function vars>,
- 'None': None,
- 'Ellipsis': Ellipsis,
- 'NotImplemented': NotImplemented,
- 'False': False,
- 'True': True,
- 'bool': bool,
- 'memoryview': memoryview,
- 'bytearray': bytearray,
- 'bytes': bytes,
- 'classmethod': classmethod,
- 'complex': complex,
- 'dict': dict,
- 'enumerate': enumerate,
- 'filter': filter,
- 'float': float,
- 'frozenset': frozenset,
- 'property': property,
- 'int': int,
- 'list': list,
- 'map': map,
- 'object': object,
- 'range': range,
- 'reversed': reversed,
- 'set': set,
- 'slice': slice,
- 'staticmethod': staticmethod,
- 'str': str,
- 'super': super,
- 'tuple': tuple,
- 'type': type,
- 'zip': zip,
- '__debug__': True,
- 'BaseException': BaseException,
- 'Exception': Exception,
- 'TypeError': TypeError,
- 'StopAsyncIteration': StopAsyncIteration,
- 'StopIteration': StopIteration,
- 'GeneratorExit': GeneratorExit,
- 'SystemExit': SystemExit,
- 'KeyboardInterrupt': KeyboardInterrupt,
- 'ImportError': ImportError,
- 'ModuleNotFoundError': ModuleNotFoundError,
- 'OSError': OSError,
- 'EnvironmentError': OSError,
- 'IOError': OSError,
- 'WindowsError': OSError,
- 'EOFError': EOFError,
- 'RuntimeError': RuntimeError,
- 'RecursionError': RecursionError,
- 'NotImplementedError': NotImplementedError,
- 'NameError': NameError,
- 'UnboundLocalError': UnboundLocalError,
- 'AttributeError': AttributeError,
- 'SyntaxError': SyntaxError,
- 'IndentationError': IndentationError,
- 'TabError': TabError,
- 'LookupError': LookupError,
- 'IndexError': IndexError,
- 'KeyError': KeyError,
- 'ValueError': ValueError,
- 'UnicodeError': UnicodeError,
- 'UnicodeEncodeError': UnicodeEncodeError,
- 'UnicodeDecodeError': UnicodeDecodeError,
- 'UnicodeTranslateError': UnicodeTranslateError,
- 'AssertionError': AssertionError,
- 'ArithmeticError': ArithmeticError,
- 'FloatingPointError': FloatingPointError,
- 'OverflowError': OverflowError,
- 'ZeroDivisionError': ZeroDivisionError,
- 'SystemError': SystemError,
- 'ReferenceError': ReferenceError,
- 'MemoryError': MemoryError,
- 'BufferError': BufferError,
- 'Warning': Warning,
- 'UserWarning': UserWarning,
- 'DeprecationWarning': DeprecationWarning,
- 'PendingDeprecationWarning': PendingDeprecationWarning,
- 'SyntaxWarning': SyntaxWarning,
- 'RuntimeWarning': RuntimeWarning,
- 'FutureWarning': FutureWarning,
- 'ImportWarning': ImportWarning,
- 'UnicodeWarning': UnicodeWarning,
- 'BytesWarning': BytesWarning,
- 'ResourceWarning': ResourceWarning,
- 'ConnectionError': ConnectionError,
- 'BlockingIOError': BlockingIOError,
- 'BrokenPipeError': BrokenPipeError,
- 'ChildProcessError': ChildProcessError,
- 'ConnectionAbortedError': ConnectionAbortedError,
- 'ConnectionRefusedError': ConnectionRefusedError,
- 'ConnectionResetError': ConnectionResetError,
- 'FileExistsError': FileExistsError,
- 'FileNotFoundError': FileNotFoundError,
- 'IsADirectoryError': IsADirectoryError,
- 'NotADirectoryError': NotADirectoryError,
- 'InterruptedError': InterruptedError,
- 'PermissionError': PermissionError,
- 'ProcessLookupError': ProcessLookupError,
- 'TimeoutError': TimeoutError,
- 'open': <function io.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)>,
- 'copyright': Copyright (c) 2001-2020 Python Software Foundation.
- All Rights Reserved.
-
- Copyright (c) 2000 BeOpen.com.
- All Rights Reserved.
-
- Copyright (c) 1995-2001 Corporation for National Research Initiatives.
- All Rights Reserved.
-
- Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
- All Rights Reserved.,
- 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
- for supporting Python development. See www.python.org for more information.,
- 'license': See https://www.python.org/psf/license/,
- 'help': Type help() for interactive help, or help(object) for help about object.,
- 'execfile': <function _pydev_imps._pydev_execfile.execfile(file, glob=None, loc=None)>,
- 'runfile': <function _pydev_bundle.pydev_umd.runfile(filename, args=None, wdir=None, is_module=False, global_vars=None)>,
- '__IPYTHON__': True,
- 'display': <function IPython.core.display_functions.display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, raw=False, clear=False, **kwargs)>,
- 'get_ipython':
>}
接着,为了过滤出class的类别type,我们可以用isinstance(t, type)判断t究竟是否为Python内置的class中的一种。
注意:上面的classinfo=type,暗示了type其实也是一种类,这个类中包括classinfo能使用的所有,当然也包括它自己。
另外,如果直接输出类class,就会导致有class前缀;比如print(int),得到的结果是
因此代码也可以改成下面的形式;最后输出和上面的一样。
- type_list = [t for t in __builtins__.__dict__.values() if isinstance(t, type)]
- # print(type_list)
- # print(type(type_list))
- type_list1 = [print(i.__name__) for i in type_list]
- print(type_list1)
有些读者可能是刚刚入门python,其实上面的x for x in X是一种推导式。