python - dir(self) 和 self.__dict__ 有什么区别

标签 python class

<分区>

Possible Duplicate:
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

有人能解释一下吗?

最佳答案

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

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

关于python - dir(self) 和 self.__dict__ 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13302917/

相关文章:

python - 计算pandas中一列列表中值的总出现次数的更快方法?

python - 我怎样才能让我的子弹看起来像是从我的枪尖中出来的?

java - 创建注释类实例的数组列表

python - pandas 与复杂类型列不兼容的形状

python - `__getattribute__` 和 `__getattr__` 中的错误处理

python - 为什么在 Folium 中使用超过 100 个圆形标记进行绘图会导致 map 空白?

javascript - 在 nav ul li h4 中使用 jQuery 添加/删除链接类

javascript - 创建自定义 Object3D 类

ios - 如何在 Swift 中临时存储图像和字符串?

c++ - 使用父类构造函数为继承的变量重新赋值