4

可能重复:
inspect.getmembers() vs __dict__.items() vs dir()

class Base():
    def __init__(self, conf):
        self.__conf__ = conf
        for i in self.__dict__:
            print i,"dict"
        for i in dir(self):
            print i,"dir"

class Test(Base):
      a = 1
      b = 2

t = Test("conf")

输出是:

__conf__ dict
__conf__ dir
__doc__ dir
__init__ dir
__module__ dir
a dir
b dir

任何人都可以解释一下吗?

4

1 回答 1

8

对象__dict__存储实例的属性。您的实例的唯一属性是__conf__因为它是您的__init__()方法中唯一的一个集合。dir()返回实例、其类及其父类的“有趣”属性的名称列表。这些包括ab来自你的Test班级和__init__来自你的Base班级,以及 Python 自动添加的一些其他属性。

类属性存储在每个类的__dict__中,因此dir()所做的是遍历继承层次结构并从每个类中收集信息。

于 2012-11-09T06:07:30.317 回答