如何获取对象的方法和属性的完整列表? [英] How to get a complete list of object's methods and attributes?

查看:50
本文介绍了如何获取对象的方法和属性的完整列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dir(re.compile(pattern)) 

不会将模式作为列表元素之一返回.即它返回:

does not return pattern as one of the lists's elements. Namely it returns:

['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']

根据手册,它应该包含

对象的属性名称,其类的属性名称,以及其属性的递归类的基类.

the object's attributes' names, the names of its class's attributes, and recursively of the attributes of its class's base classes.

它也说

列表不一定完整.

有没有办法获得完整的列表?我一直认为 dir 返回一个完整的列表,但显然它没有......

Is there a way to get the complete list? I always assumed that dir returns a complete list but apparently it does not...

另外:有没有办法只列出属性?还是只有方法?

Also: is there a way to list only attributes? Or only methods?

这实际上是 python 中的一个错误 -> 据说它已在 3.0 分支中修复(可能也在 2.6 中)

推荐答案

对于完整属性列表,简短的回答是:不.问题是属性实际上被定义为 getattr 内置函数接受的参数.由于用户可以重新实现 __getattr__,突然允许任何类型的属性,因此没有可能的通用方法来生成该列表.dir 函数返回 __dict__ 属性中的键,即如果 __getattr__ 方法未重新实现,则所有可访问的属性.

For the complete list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the getattr built-in function. As the user can reimplement __getattr__, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The dir function returns the keys in the __dict__ attribute, i.e. all the attributes accessible if the __getattr__ method is not reimplemented.

对于第二个问题,真的没有意义.实际上,方法是可调用的属性,仅此而已.您可以过滤可调用属性,并使用 inspect 模块确定类方法、方法或函数.

For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the inspect module determine the class methods, methods or functions.

这篇关于如何获取对象的方法和属性的完整列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆