How to get actual list of names of object if custom __dir__ implemented?
官方文件说:
If the object has a method named
__dir__() , this method will be called
and must return the list of attributes. This allows objects that
implement a custom__getattr__() or__getattribute__() function to
customize the waydir() reports their attributes.
如果实现自定义
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class С(object): __slots__ = ['atr'] def __dir__(self): return ['nothing'] def method(self): pass def __init__(self): self.atr = 'string' c = C() print dir(f) #If we try this - well get ['nothing'] returned by custom __dir__() print inspect.getmembers(f) #Here we get [] print f.__dict__ #And here - exception will be raised because of __slots__ |
在这种情况下,如何获取对象名称列表?
原始问题的答案——
这是
1 2 3 4 5 6 7 8 9 10 11 12 13 | def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" results = [] for key in dir(object): try: value = getattr(object, key) except AttributeError: continue if not predicate or predicate(value): results.append((key, value)) results.sort() return results |
从中我们看到它正在使用
根据这个答案,不可能总是得到一个完整的属性列表,但是在某些情况下,我们仍然可以肯定地得到它们/得到足够的有用的。
来自文档:
If the object does not provide
__dir__() , the function tries its best
to gather information from the object’s__dict__ attribute, if
defined, and from its type object. The resulting list is not
necessarily complete, and may be inaccurate when the object has a
custom__getattr__() .
因此,如果您不使用
如果您使用的是
您可能需要一个不同的解决方案,具体取决于用例,但是如果您只是想轻松地找到方法,您可以简单地使用内置的
这里有一个以上方法的替代方法:要得到一个忽略用户定义的
马修在另一个答案中指出,
1 2 3 4 5 6 7 8 9 10 11 12 | >>> class C: >>> def foo(self): >>> pass >>> def __dir__(self): >>> return ['test'] >>> >>> import inspect >>> c = C() >>> dir(c) ['test'] >>> inspect.getmembers(c) [] |