首页 > 解决方案 > 如何访问类并获取可用操作的 dir()?

问题描述

我一直在尝试从 re.search 访问匹配对象的可用函数。我正在寻找一种类似于我可以执行 dir(str) 的方法并且我可以找到 .replace。

这是我的 re 模块的 dir() 和我尝试过的一些事情:

>>> import re
>>> m = re.search('x', 'x')
>>> dir(re)
['DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 
'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', 
'_MAXCACHE', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 
'__package__', '__version__', '_alphanum', '_cache', '_cache_repl', 
'_compile', '_compile_repl', '_expand', '_locale', '_pattern_type', 
'_pickle', '_subx', 'compile', 'copy_reg', 'error', 'escape', 'findall', 
'finditer', 'match', 'purge', 'search', 'split', 'sre_compile', 
'sre_parse', 'sub', 'subn', 'sys', 'template']

我想进入这个菜单而不必创建匹配对象:

>>> dir(m)
['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__', 
'__format__', '__getattribute__', '__hash__', '__init__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', 
'__str__', '__subclasshook__', 'end', 'endpos', 'expand', 'group', 
'groupdict', 'groups', 'lastgroup', 'lastindex', 'pos', 're', 'regs', 
'span', 'start', 'string']

有没有办法从 dir(m) 出发并能够找出如何提升一个级别?这样我就可以追溯到模块和功能。就像我要执行 dir(re.search.func_dict) 一样,我怎样才能找出我需要在 dir() 中输入什么来取回包含 func_dict() 的列表?

>>> dir(re.Match)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Match'

我看到了关于 _sre.SRE._Match 的东西,但是我如何找到它的位置以便获得更多信息?

>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, 'm': <_sre.SRE_Match 
object at 0xb7b0d8a8>, '__package__': None, 're': <module 're' from 
'/usr/lib/python2.7/re.pyc'>, '__name__': '__main__', '__doc__': None}

我曾尝试使用检查功能,但给我任何信息的唯一功能是 inspect.getmembers(re) 但这只是我不明白的一大堆东西。

在学习编程课程之后,我是一个完整的新手,除了我编写的一些程序之外,我没有 Python 基础知识。我一直在尝试使用 dir() 和 help() 来学习很多东西。我非常感谢您的帮助。

标签: python

解决方案


这是迄今为止我得到的最接近的东西:

>>> import re, inspect

>>> inspect.getmembers(re,inspect.isclass)
[('Scanner', <class re.Scanner at 0xb7b7bcec>), ('_pattern_type', <type 
'_sre.SRE_Pattern'>), ('error', <class 'sre_constants.error'>)]

>>> from re import _pattern_type

>>> dir(_pattern_type)
['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__', '__format__', 
'__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'findall', 
'finditer', 'flags', 'groupindex', 'groups', 'match', 'pattern', 'scanner', 'search', 
'split', 'sub', 'subn']

推荐阅读