How to get a complete list of object's methods and attributes?
1 | dir(re.compile(pattern)) |
不返回作为列表元素之一的模式。即返回:
1 | ['__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.
它还说
The list is not necessarily complete.
有没有办法得到完整的清单?我一直以为dir会返回一个完整的列表,但显然它不会…
还有:有没有只列出属性的方法?或者只是方法?
编辑:这实际上是python中的一个bug->假设它是在3.0分支中修复的(也可能是在2.6中)
for the list of the short是完整的,答案是:不。the is that the属性真的是问题定义as the accepted by the
for the second question它does not make,真感。其实,什么方法是callable属性更多。虽然你可以使用布尔属性,callable filter,the
that is the new method has been
欧洲经济区:P></
- http:/ / / / 2.6.html docs.python.org whatsnew changes(其他语言#涡卷小唐氏位)
- bugs.python.org http:/ / / issue1591665
here is to the answers of实用之外pierrebdr和弹性模量:P></
- 在Python 2.6>=
dir() 类和新的风格,似乎是不够的。 换旧风格的类,我们可以做什么,至少在标准模块:支持表完成does to to
dir() 之外,寻找__class__ ,然后去__bases__ :for itsP></1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31# code borrowed from the rlcompleter module
# tested under Python 2.6 ( sys.version = '2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3]' )
# or: from rlcompleter import get_class_members
def get_class_members(klass):
ret = dir(klass)
if hasattr(klass,'__bases__'):
for base in klass.__bases__:
ret = ret + get_class_members(base)
return ret
def uniq( seq ):
""" the 'set()' way ( use dict when there's no set )"""
return list(set(seq))
def get_object_attrs( obj ):
# code borrowed from the rlcompleter module ( see the code for Completer::attr_matches() )
ret = dir( obj )
## if"__builtins__" in ret:
## ret.remove("__builtins__")
if hasattr( obj, '__class__'):
ret.append('__class__')
ret.extend( get_class_members(obj.__class__) )
ret = uniq( ret )
return ret
(试验代码和输出是消去for简洁风格,但基本上我们为新对象似乎to have the same as for
补充:only toP></
他们的解决方案比其他方式提供
二级属性列表或not,is important to do the sifting它自己,因为有时你可能想收购主导变量与内部sift underscores
here is an example:P></
1 2 3 4 5 6 | \\...\\torchfun.py in traverse(self, mod, search_attributes) 445 if prefix in traversed_mod_names: 446 continue 447 names = dir(m) 448 for name in names: 449 obj = getattr(m,name) |
对象描述符包括:
pytorch the author of the method to something that修饰
如果你想在导线的可靠计划的对象是要记住that of an,每个语言标准和可能overridden can be not hold and may be unreliable,每个会议。P></
这样做的无知,useful for custom to which对象属性:你继续增P></
1 2 | class Obj: pass obj = Obj() |
属性:add someP></
1 2 | obj.name = 'gary' obj.age = 32 |
然后,to obtain the only with a custom属性:词典P></
1 2 3 | {key: value for key, value in obj.__dict__.items() if not key.startswith("__")} # {'name': 'gary', 'age': 32} |