程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

【Python】 - Python的內置函數isinstance()中的參數classinfo一共有多少種,可以判斷多少種類型?

編輯:Python

一、參考來源

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)])

可以得到。

[<class '_frozen_importlib.BuiltinImporter'>, <class 'bool'>, <class 'memoryview'>, <class 'bytearray'>, <class 'bytes'>, <class 'classmethod'>, <class 'complex'>, <class 'dict'>, <class 'enumerate'>, <class 'filter'>, <class 'float'>, <class 'frozenset'>, <class 'property'>, <class 'int'>, <class 'list'>, <class 'map'>, <class 'object'>, <class 'range'>, <class 'reversed'>, <class 'set'>, <class 'slice'>, <class 'staticmethod'>, <class 'str'>, <class 'super'>, <class 'tuple'>, <class 'type'>, <class 'zip'>, <class 'BaseException'>, <class 'Exception'>, <class 'TypeError'>, <class 'StopAsyncIteration'>, <class 'StopIteration'>, <class 'GeneratorExit'>, <class 'SystemExit'>, <class 'KeyboardInterrupt'>, <class 'ImportError'>, <class 'ModuleNotFoundError'>, <class 'OSError'>, <class 'OSError'>, <class 'OSError'>, <class 'OSError'>, <class 'EOFError'>, <class 'RuntimeError'>, <class 'RecursionError'>, <class 'NotImplementedError'>, <class 'NameError'>, <class 'UnboundLocalError'>, <class 'AttributeError'>, <class 'SyntaxError'>, <class 'IndentationError'>, <class 'TabError'>, <class 'LookupError'>, <class 'IndexError'>, <class 'KeyError'>, <class 'ValueError'>, <class 'UnicodeError'>, <class 'UnicodeEncodeError'>, <class 'UnicodeDecodeError'>, <class 'UnicodeTranslateError'>, <class 'AssertionError'>, <class 'ArithmeticError'>, <class 'FloatingPointError'>, <class 'OverflowError'>, <class 'ZeroDivisionError'>, <class 'SystemError'>, <class 'ReferenceError'>, <class 'MemoryError'>, <class 'BufferError'>, <class 'Warning'>, <class 'UserWarning'>, <class 'DeprecationWarning'>, <class 'PendingDeprecationWarning'>, <class 'SyntaxWarning'>, <class 'RuntimeWarning'>, <class 'FutureWarning'>, <class 'ImportWarning'>, <class 'UnicodeWarning'>, <class 'BytesWarning'>, <class 'ResourceWarning'>, <class 'ConnectionError'>, <class 'BlockingIOError'>, <class 'BrokenPipeError'>, <class 'ChildProcessError'>, <class 'ConnectionAbortedError'>, <class 'ConnectionRefusedError'>, <class 'ConnectionResetError'>, <class 'FileExistsError'>, <class 'FileNotFoundError'>, <class 'IsADirectoryError'>, <class 'NotADirectoryError'>, <class 'InterruptedError'>, <class 'PermissionError'>, <class 'ProcessLookupError'>, <class '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=<class '_frozen_importlib.BuiltinImporter'>),
'__build_class__': <function __build_class__>,
'__import__': <bound method ImportHookManager.do_import of <module '_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': <bound method InteractiveShell.get_ipython of <_pydev_bundle.pydev_ipython_console_011.PyDevTerminalInteractiveShell object at 0x000001B4231FB6D0>>}

接著,為了過濾出class的類別type,我們可以用isinstance(t, type)判斷t究竟是否為Python內置的class中的一種。

注意:上面的classinfo=type,暗示了type其實也是一種類,這個類中包括classinfo能使用的所有,當然也包括它自己。

另外,如果直接輸出類class,就會導致有class前綴;比如print(int),得到的結果是<class 'int'>;為了消除這個前綴,我們可以用類class的__name__屬性;比如print(int.__name__),輸出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是一種推導式。


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved