官方文档说:
如果对象有一个名为 的方法
__dir__()
,该方法将被调用并且必须返回属性列表。这允许实现自定义__getattr__()
或__getattribute__()
功能的对象自定义dir()
报告其属性的方式。
如果自定义__dir__
实现,由另一个函数返回的结果inspect.getmembers()
也会受到影响。
例如:
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__
在这种情况下,如何获取对象名称列表?