运行结果: {‘module’: ‘main’, ‘a’: 0, ‘b’: 1, ‘init’: <function A.init at 0x000001C659BBE620>, ‘test’: <function A.test at 0x000001C659BBE6A8>, ‘static_test’: <staticmethod object at 0x000001C659B19DA0>, ‘class_test’: <classmethod object at 0x000001C659B19E10>, ‘dict’: <attribute ‘dict’ of ‘A’ objects>, ‘weakref’: <attribute ‘weakref’ of ‘A’ objects>, ‘doc’: None}
{‘a’: 2, ‘b’: 3}
可以看出 :类的静态函数、类函数、普通函数、全局变量以及一些内置的属性都是放在类__dict__里的 对象的__dict__中存储了一些self.xxx的一些东西
python一些内置对象没有__dict__ 属性 如 数字 ,列表, 字典
num = 1 print(num.__dict__)会报错,说int 类型没有__dict__ 属性
运行结果
{'__module__': '__main__', 'a': 0, 'b': 1, '__init__': <function Parent.__init__ at 0x0000013F9349E620>, 'p_test': <function Parent.p_test at 0x0000013F9349E6A8>, '__dict__': <attribute '__dict__' of 'Parent' objects>, '__weakref__': <attribute '__weakref__' of 'Parent' objects>, '__doc__': None} {'__module__': '__main__', 'a': 4, 'b': 5, '__init__': <function Child.__init__ at 0x0000013F9349E730>, 'c_test': <function Child.c_test at 0x0000013F9349E7B8>, 'p_test': <function Child.p_test at 0x0000013F9349E840>, '__doc__': None} {'a': 2, 'b': 3} {'a': 2, 'b': 3} 1372535955248 1372565655768内置的数据类型没有__dict__属性 每个类有自己的__dict__属性,就算存着继承关系,父类的__dict__ 并不会影响子类的__dict__ 对象也有自己的__dict__属性, 存储self.xxx 信息,父子类对象__dict__ 不相同 (id不一样)
运行: user {‘name’: ‘pei’, ‘phone’: ‘16730818188’} user1 {‘name’: ‘pei’, ‘phone’: ‘16730818188’}
利用__dict__的特性,上面的类可以用如下的代替,代码量大大减少 免了在__init__方法中类似于self.something = something的方法,使用自动化实例变量