【问题标题】:Can't get an object's class name in Python无法在 Python 中获取对象的类名
【发布时间】:2011-01-18 23:10:52
【问题描述】:

我正在使用 isinstance 检查参数类型,但找不到正则表达式模式对象的类名:

>>> import re
>>> x = re.compile('test')
>>> x.__class__.__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __class__

...

>>> type(x)
<type '_sre.SRE_Pattern'>
>>> isinstance(x, _sre.SRE_Pattern)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_sre' is not defined
>>>
>>>
>>> isinstance(x, '_sre.SRE_Pattern')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
>>> 

有什么想法吗?

【问题讨论】:

  • 你做了import _sre吗? NameError 有什么让您惊讶的地方?
  • @SilentGhost: _sre 是一个内部模块,不会向外部泄露SRE_Pattern
  • @poke:如果你不导入_sre,你不会知道的
  • @SilentGhost:它没有——现在仍然没有——一个对象不知道自己或者它会在一个外部模块中。
  • @zum: x.__class__.__name__ 在 py3k 中对我来说很好用。我不确定我是否在关注你的对象知道自己收费。

标签: python class object types isinstance


【解决方案1】:

你可以这样做:

import re

pattern_type = type(re.compile("foo"))

if isinstance(your_object, pattern_type):
   print "It's a pattern object!"

惯用的方法是尝试将其用作模式对象,如果不是,则处理产生的异常。

【讨论】:

  • +1,这应该是最安全的方法。考虑到实际的正则表达式实现在 C 核心内部,其他一切都会很危险。
【解决方案2】:
In : x = re.compile('test')
In : isinstance(x, type(x))
Out: True

In [14]: type(type(x))
Out[14]: <type 'type'>

我认为它与类型/对象的附属功能和 re 模块的实现有关。你可以阅读一篇不错的文章here

【讨论】:

    猜你喜欢
    • 2014-01-22
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 2020-02-24
    • 1970-01-01
    • 2019-07-31
    • 2010-10-31
    相关资源
    最近更新 更多