假设你有一门课>>> class Cls(object):
... foo = 1
... bar = 'hello'
... def func(self):
... return 'call me'
...
>>> obj = Cls()
对对象调用dir将返回该对象的所有属性,包括python特殊属性。尽管有些对象属性是可调用的,例如方法。>>> dir(obj)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar', 'foo', 'func']
你总是可以通过使用列表理解过滤掉特殊的方法。>>> [a for a in dir(obj) if not a.startswith('__')]
['bar', 'foo', 'func']
或者如果您喜欢映射/过滤器。>>> filter(lambda a: not a.startswith('__'), dir(obj))
['bar', 'foo', 'func']
如果要过滤掉这些方法,可以使用内置的callable作为检查。>>> [a for a in dir(obj) if not a.startswith('__') and not callable(getattr(obj, a))]
['bar', 'foo']
您还可以使用检查类与其实例对象之间的差异。>>> set(dir(Cls)) - set(dir(object))
set(['__module__', 'bar', 'func', '__dict__', 'foo', '__weakref__'])