^{}基本上是一个方便的方法,它不应该返回所有内容,它的基本功能是递归地返回在类及其基的字典中找到的所有内容。在def dir(*args):
...
elif isinstance(obj, (types.TypeType, types.ClassType)):
# Don't look at __class__, as metaclass methods would be confusing.
return sorted(_classdir(obj))
...
def _classdir(klass):
"""Return a set of the accessible attributes of class/type klass.
This includes all attributes of klass and all of the base classes
recursively.
"""
names = set()
ns = getattr(klass, '__dict__', None)
if ns is not None:
names.update(ns)
bases = getattr(klass, '__bases__', None)
if bases is not None:
# Note that since we are only interested in the keys, the order
# we merge classes is unimportant
for base in bases:
names.update(_classdir(base))
return names
由于每个类基本上都继承自object,因此您将看到包含一些dunder方法,因为它们实际上是object字典的一部分:
^{2}$
Now what about __bases__ and other missing items?>>> isinstance(type, object)
True
>>> isinstance(object, type)
True
>>> issubclass(type, object)
True
>>> issubclass(object, type)
False
>>> type.mro(object)
[]
>>> type.mro(type)
[, ]
因此,所有属性,如__bases__,__ge__等实际上都是type的一部分:>>> list(type.__dict__)
['__module__', '__abstractmethods__', '__getattribute__', '__weakrefoffset__', '__dict__', '__lt__', '__init__', '__setattr__', '__subclasses__', '__new__', '__base__', '__mro__', 'mro', '__dictoffset__', '__call__', '__itemsize__', '__ne__', '__instancecheck__', '__subclasscheck__', '__gt__', '__name__', '__eq__', '__basicsize__', '__bases__', '__flags__', '__doc__', '__delattr__', '__le__', '__repr__', '__hash__', '__ge__']
因此,当我们A.__bases__时,我们实际上是在查找descriptor on type of ^{},即type:>>> A.__bases__
(,)
>>> type(A).__dict__['__bases__'].__get__(A, type)
(,)
因此,由于A是{}的一个实例,这些方法不是它自己的字典的一部分,而是它的类型字典的一部分。在>> class A(object):
... spam = 'eggs'
...
>>> a = A()
>>> a.foo = 100
>>> a.bar = 200
>>> a.__dict__
{'foo': 100, 'bar': 200}
>>> A.__dict__
dict_proxy({'__dict__': , '__module__': '__main__', '__weakref__': , '__doc__': None, 'spam': 'eggs'})
由于type是object的子类,对type的dir()调用将包含来自{}的一些项:>>> set(dir(type)) - set(type.__dict__)
set(['__reduce_ex__', '__str__', '__format__', '__reduce__', '__class__', '__subclasshook__', '__sizeof__'])