0

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

何か案は?

4

2 に答える 2

4

あなたはこれを行うことができます:

import re

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

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

慣用的な方法は、それをパターンオブジェクトとして使用しようとし、そうでない場合は結果の例外を処理することです。

于 2011-01-18T23:16:26.593 に答える
0
In : x = re.compile('test')
In : isinstance(x, type(x))
Out: True

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

タイプ/オブジェクトのサブティリティとreモジュールの実装に関連していると思います。ここで素敵な記事を読むことができます。

于 2011-01-18T23:27:24.027 に答える