dir(re.compile(pattern))
不返回pattern作为列表的元素之一。即它返回:
['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']
根据手册,它应该包含
对象的属性名称
类属性的名称,以及
其属性的递归
类的基类。
它还说
这个列表并不一定是完整的。
有没有办法得到完整的清单?我总是假设dir返回一个完整的列表,但显然它不是…
还有:是否有一种方法只列出属性?还是只有方法?
编辑:这实际上是python中的一个bug ->应该在3.0分支中修复了(可能在2.6中也有)
只是补充:
dir() is the most powerful/fundamental tool. (Most recommended)
Solutions other than dir() merely provide their way of dealing the output of dir().
Listing 2nd level attributes or not, it is important to do the sifting by yourself, because sometimes you may want to sift out internal vars with leading underscores __, but sometimes you may well need the __doc__ doc-string.
__dir__() and dir() returns identical content.
__dict__ and dir() are different. __dict__ returns incomplete content.
IMPORTANT: __dir__() can be sometimes overwritten with a function, value or type, by the author for whatever purpose.
Here is an example:
\\...\\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)
TypeError: descriptor __dir__ of 'object' object needs an argument
The author of PyTorch modified the __dir__() method to something that requires an argument. This modification makes dir() fail.
If you want a reliable scheme to traverse all attributes of an object, do remember that every pythonic standard can be overridden and may not hold, and every convention may be unreliable.
这就是我怎么做的,对你不断添加属性的简单自定义对象很有用:
给定一个用obj = type(" obj ",(object,),{})创建的对象,或者简单地通过:
class Obj: pass
obj = Obj()
添加一些属性:
obj.name = 'gary'
obj.age = 32
然后,获取一个只有自定义属性的字典:
{key: value for key, value in obj.__dict__.items() if not key.startswith("__")}
# {'name': 'gary', 'age': 32}
下面是对PierreBdR和Moe的回答的补充:
For Python >= 2.6 and new-style classes, dir() seems to be enough.
For old-style classes, we can at least do what a standard module does to support tab completion: in addition to dir(), look for __class__, and then to go for its __bases__:
# code borrowed from the rlcompleter module
# tested under Python 2.6 ( sys.version = '2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[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
(为了简洁起见,删除了测试代码和输出,但基本上对于新样式的对象,我们似乎对get_object_attrs()得到了与dir()相同的结果,而对于旧样式的类,dir()输出的主要添加似乎是__class__属性。)
只是补充:
dir() is the most powerful/fundamental tool. (Most recommended)
Solutions other than dir() merely provide their way of dealing the output of dir().
Listing 2nd level attributes or not, it is important to do the sifting by yourself, because sometimes you may want to sift out internal vars with leading underscores __, but sometimes you may well need the __doc__ doc-string.
__dir__() and dir() returns identical content.
__dict__ and dir() are different. __dict__ returns incomplete content.
IMPORTANT: __dir__() can be sometimes overwritten with a function, value or type, by the author for whatever purpose.
Here is an example:
\\...\\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)
TypeError: descriptor __dir__ of 'object' object needs an argument
The author of PyTorch modified the __dir__() method to something that requires an argument. This modification makes dir() fail.
If you want a reliable scheme to traverse all attributes of an object, do remember that every pythonic standard can be overridden and may not hold, and every convention may be unreliable.