Python __dict__
一、无处不在的__dict__
类的__dict__
、类对象的__dict__
。
class A():
a = 0
b = 1
def __init__(self):
self.a = 2
self.b = 3
def test(self):
print('a normal func.')
@staticmethod
def static_test():
print('a static func.')
@classmethod
def class_test(cls):
print('a class func.')
obj = A()
print(A.__dict__)
print(obj.__dict__)
输出:
{'__module__': '__main__', 'a': 0, 'b': 1, '__init__': <function A.__init__ at 0x00000169C2E452F0>, 'test': <function A.test at 0x00000169C2E45400>, 'static_test': <staticmethod object at 0x00000169C2E494A8>, 'class_test': <classmethod object at 0x00000169C2E494E0>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
{'a': 2, 'b': 3}
类的静态函数、类函数、普通函数、全局变量、一些内置的属性都放在类__dict__
里。
对象__dict__
中存储的是一些self.xxx
。
二、Python里什么没有__dict__
属性
一些内置的数据类型没有__dict__
属性。
num = 3
lst = []
dict = {}
print(num.__dict__)
print(lst.__dict__)
print(dict.__dict__)
输出:
AttributeError: 'list' object has no attribute '__dict__'
AttributeError: 'list' object has no attribute '__dict__'
AttributeError: 'dict' object has no attribute '__dict__'
三、继承时的__dict__
属性
子类有自己的__dict__
,父类有自己的__dict__
。
子类的全局变量和函数放在子类的dict中,父类的放在父类dict中。
class Parent():
a = 0
b = 1
def __init__(self):
self.a = 2
self.b = 3
def p_test(self):
pass
class Child(Parent):
a = 4
b = 5
def __init__(self):
super().__init__()
def c_test(self):
pass
def p_test(self):
pass
p = Parent()
c = Child()
print(Parent.__dict__)
print(Child.__dict__)
print(p.__dict__)
print(c.__dict__)
输出:
{'__module__': '__main__', 'a': 0, 'b': 1, '__init__': <function Parent.__init__ at 0x00000291EFD052F0>, 'p_test': <function Parent.p_test at 0x00000291EFD05400>, '__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 0x00000291F0D4BB70>, 'c_test': <function Child.c_test at 0x00000291F0D4BBF8>, 'p_test': <function Child.p_test at 0x00000291F0D4BC80>, '__doc__': None}
{'a': 2, 'b': 3}
{'a': 2, 'b': 3}
总结:
- 内置的数据类型没有
__dict__
属性。 - 每个类有自己的
__dict__
属性,就算存着继承关系,父类的__dict__
并不会影响子类的__dict__。
- 对象也有自己的
__dict__
属性, 存储self.xxx 信息,父子类对象公用__dict__。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)