gpt4 book ai didi

python - 如何获取所有 Python 类型的列表(以编程方式)?

转载 作者:太空狗 更新时间:2023-10-30 00:52:20 25 4
gpt4 key购买 nike

a recent question 中的讨论,min/max() 需要对象进行比较,这让我想知道如何找到哪些 Python 类型支持特定方法(__cmp__,或者 __lt__ - 具体细节不重要)。

关键似乎是能够获取所有类型的列表,首先。然后我可以简单地检查 hasattr(thisType, '__cmp__')。那么我该如何枚举所有的数据类型呢?

最佳答案

>>> try: import __builtin__ as b
... except ImportError: import builtins as b
...
>>> builtin_types= [t
... for t in b.__dict__.values()
... if isinstance(t, type)]
>>> import pprint
>>> pprint.pprint(sorted(builtin_types, key=repr))
[<type 'basestring'>,
<type 'bool'>,
<type 'buffer'>,
<type 'bytearray'>,
<type 'classmethod'>,
<type 'complex'>,
<type 'dict'>,
<type 'enumerate'>,
<type 'exceptions.ArithmeticError'>,
<type 'exceptions.AssertionError'>,
<type 'exceptions.AttributeError'>,
<type 'exceptions.BaseException'>,
<type 'exceptions.BufferError'>,
<type 'exceptions.BytesWarning'>,
<type 'exceptions.DeprecationWarning'>,
<type 'exceptions.EOFError'>,
<type 'exceptions.EnvironmentError'>,
<type 'exceptions.Exception'>,
<type 'exceptions.FloatingPointError'>,
<type 'exceptions.FutureWarning'>,
<type 'exceptions.GeneratorExit'>,
<type 'exceptions.IOError'>,
<type 'exceptions.ImportError'>,
<type 'exceptions.ImportWarning'>,
<type 'exceptions.IndentationError'>,
<type 'exceptions.IndexError'>,
<type 'exceptions.KeyError'>,
<type 'exceptions.KeyboardInterrupt'>,
<type 'exceptions.LookupError'>,
<type 'exceptions.MemoryError'>,
<type 'exceptions.NameError'>,
<type 'exceptions.NotImplementedError'>,
<type 'exceptions.OSError'>,
<type 'exceptions.OverflowError'>,
<type 'exceptions.PendingDeprecationWarning'>,
<type 'exceptions.ReferenceError'>,
<type 'exceptions.RuntimeError'>,
<type 'exceptions.RuntimeWarning'>,
<type 'exceptions.StandardError'>,
<type 'exceptions.StopIteration'>,
<type 'exceptions.SyntaxError'>,
<type 'exceptions.SyntaxWarning'>,
<type 'exceptions.SystemError'>,
<type 'exceptions.SystemExit'>,
<type 'exceptions.TabError'>,
<type 'exceptions.TypeError'>,
<type 'exceptions.UnboundLocalError'>,
<type 'exceptions.UnicodeDecodeError'>,
<type 'exceptions.UnicodeEncodeError'>,
<type 'exceptions.UnicodeError'>,
<type 'exceptions.UnicodeTranslateError'>,
<type 'exceptions.UnicodeWarning'>,
<type 'exceptions.UserWarning'>,
<type 'exceptions.ValueError'>,
<type 'exceptions.Warning'>,
<type 'exceptions.ZeroDivisionError'>,
<type 'file'>,
<type 'float'>,
<type 'frozenset'>,
<type 'int'>,
<type 'list'>,
<type 'long'>,
<type 'object'>,
<type 'property'>,
<type 'reversed'>,
<type 'set'>,
<type 'slice'>,
<type 'staticmethod'>,
<type 'str'>,
<type 'str'>,
<type 'super'>,
<type 'tuple'>,
<type 'type'>,
<type 'unicode'>,
<type 'xrange'>]

关于python - 如何获取所有 Python 类型的列表(以编程方式)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3210238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com