dir()不会尝试提供完整的输出,只是在交互式解释器中有用的合理近似值.
dir在输出中不包含__mro__和mro的原因可以在源代码中找到,在Objects/object.c at line 1812下:
/* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.
We deliberately don't suck up its __class__,as methods belonging to the
metaclass would probably be more confusing than helpful.
*/
static PyObject *
_specialized_dir_type(PyObject *obj)
事实证明,mro方法和__mro__属性实际上是元类的属性,即类型:
>>> '__mro__' in object.__dict__
False
>>> '__mro__' in type.__dict__
True
>>> 'mro' in object.__dict__
False
>>> 'mro' in type.__dict__
True
因此它们没有显示在dir的输出中.这是否合理取决于.我相信大多数时候你真的不想看到元类定义的内容,因为它们是元类的内部结构.
如dir()的文档中所述,您可以自定义其输出,定义__dir__方法.但是这适用于类的实例:
class A(object):
def __dir__(self):
return ['a','b','c']
print(dir(A()),dir(A))
输出:
(['a','c'],['__class__','__delattr__','__dict__','__dir__','__doc__','__format__','__getattribute__','__hash__','__init__','__module__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','__weakref__'])
如果您还要自定义dir(A)的输出,则必须使用自定义元类:
class MyMeta(type):
def __dir__(self):
return ['a','c']
class A(object,metaclass=MyMeta):
# __metaclass__ = MyMeta # in python 2
def __dir__(self):
return ['a','c','d']
print(dir(A()),'d'],['a','c'])