我们都知道Python一切皆对象,那么Python究竟是怎么管理对象的呢?
1、无处不在的__dict__
首先看一下类的__dict__属性和类对象的__dict__属性
#-*- coding: utf-8 -*-
classA(object):"""Class A."""a=0
b= 1
def __init__(self):
self.a= 2self.b= 3
deftest(self):print 'a normal func.'@staticmethoddefstatic_test(self):print 'a static func.'@classmethoddefclass_test(self):print 'a calss func.'obj=A()print A.__dict__
print obj.__dict__
运行结果如下:
{'a': 0, '__module__': '__main__', 'b': 1, 'class_test': , '__dict__': , '__init__': , 'test': , '__weakref__': , '__doc__': '\n Class A.\n', 'static_test': }
{'a': 2, 'b': 3}
由此可见, 类的静态函数、类函数、普通函数、全局变量以及一些内置的属性都是放在类__dict__里的
对象的__dict__中存储了一些self.xxx的一些东西
2、Python里什么没有__dict__属性
虽然说一切皆对象,但对象也有不同,就好比不是每个人的女朋友都是一个人一样,一些内置的数据类型是没有__dict__属性的,如下:
num = 3ll=[]
dd={}print num.__dict__
print ll.__dict__
print dd.__dict__
当我们运行这样的代码时,解释器就会告诉我们
Traceback (most recent call last):
File"f:\python\test.py", line 54, in
print num.__dict__AttributeError:'int' object has no attribute '__dict__'Traceback (most recent call last):
File"f:\python\test.py", line 55, in
print ll.__dict__AttributeError:'list' object has no attribute '__dict__'Traceback (most recent call last):
File"f:\python\test.py", line 56, in
print dd.__dict__AttributeError:'dict' object has no attribute '__dict__'
int, list, dict等这些常用的数据类型是没有__dict__属性的,其实这是可预料的,就算给了它们dict属性也没啥用,毕竟它们只是用来做数据容器的。
3、发生继承时候的__dict__属性
子类有自己的__dict__, 父类也有自己的__dict__,子类的全局变量和函数放在子类的dict中,父类的放在父类dict中。
#-*- coding: utf-8 -*-
classParent(object):
a=0
b= 1
def __init__(self):
self.a= 2self.b= 3
defp_test(self):pass
classChild(Parent):
a= 4b= 5
def __init__(self):
super(Child, self).__init__()
# self.a= 6# self.b= 7
defc_test(self):pass
defp_test(self):passp=Parent()
c=Child()print Parent.__dict__
print Child.__dict__
print p.__dict__
print c.__dict__
运行上面的代码,结果入下:
{'a': 0, '__module__': '__main__', 'b': 1, '__dict__': , 'p_test': , '__weakref__': , '__doc__': None, '__init__': }
{'a': 4, 'c_test': , '__module__': '__main__', 'b': 5, 'p_test': , '__doc__': None, '__init__': }
{'a': 2, 'b': 3}
{'a': 2, 'b': 3}
1)上段输出结果中,用红色字体标出的是类变量和函数,由结果可知,每个类的类变量、函数名都放在自己的__dict__中
2) 再来看一下实力变量的__dict__中,由蓝色字体标识,父类和子类对象的__dict__是公用的
总结:
1) 内置的数据类型没有__dict__属性
2) 每个类有自己的__dict__属性,就算存着继承关系,父类的__dict__ 并不会影响子类的__dict__
3) 对象也有自己的__dict__属性, 存储self.xxx 信息,父子类对象公用__dict__
勘误:
多谢几位同学的@TianYuanSX, @企鹅lin, @halo1234, 父子类对象不是公用dict,验证方法3楼已经说了;同时也可以用id(p.__dict__) id(c.__dict__) 验证,两个确实不同。