1.类的__dict__属性和类对象的__dict__属性
class Parent(object): a = 'a' b = 1 def __init__(self): self.a = 'A' self.b = 1.1 def print_info(self): print('a = %s , b = %s' % (self.a, self.b)) @staticmethod def static_test(self): print 'a static func.' @classmethod def class_test(self): print 'a calss func.' # class Son(Parent): p = Parent() print(Parent.__dict__) print(p.__dict__)
运行结果如下:
{'__module__': '__main__', 'a': 'a', 'b': 1, '__init__': <function Parent.__init__ at 0x0000000002168950>, 'print_info': <function Parent.print_info at 0x00000000021689D8>, 'static_test': <staticmethod object at 0x00000000021677B8>, 'class_test': <classmethod object at 0x0000000002167DD8>, '__dict__': <attribute '__dict__' of 'Parent' objects>, '__weakref__': <attribute '__weakref__' of 'Parent' objects>, '__doc__': None}
{'a': 'A', 'b': 1.1}
由此可见, 类的静态函数、类函数、普通函数、全局变量以及一些内置的属性都是放在类__dict__里的
对象的__dict__中存储了一些self.xxx的一些东西
2.存在继承关系的
子类有自己的__dict__, 父类也有自己的__dict__,子类的全局变量和函数放在子类的dict中,父类的放在父类dict中。
class Parent(object): a = 'a' b = 1 def __init__(self): self.a = 'A' self.b = 1.1 class Son(Parent): a = 'b' b = 2 def __init__(self): self.b = 2.2 self.a = 'B' p = Parent() print(Parent.__dict__) print(p.__dict__) s = Son() print(Son.__dict__) print(s.__dict__)
运行上面的代码,结果入下:
{'__module__': '__main__', 'a': 'a', 'b': 1, '__init__': <function Parent.__init__ at 0x0000000002278950>, '__dict__': <attribute '__dict__' of 'Parent' objects>, '__weakref__': <attribute '__weakref__' of 'Parent' objects>, '__doc__': None} {'a': 'A', 'b': 1.1} {'__module__': '__main__', 'a': 'b', 'b': 2, '__init__': <function Son.__init__ at 0x00000000022789D8>, '__doc__': None} {'b': 2.2, 'a': 'B'}
再看内置的数据类型, 类 == 类型,但内置数据是没有__dict__属性
num = 3 ll = [] dd = {}
运行结果:
Traceback (most recent call last): File "D:/python_studay/day8/__dict__属性详解.py", line 31, in <module> num.__dict__ AttributeError: 'int' object has no attribute '__dict__'
总结:
1.内置的数据类型是没有__dict__属性
2.类的__dict__存放类这个名称空间里有的数据,但类实例化的对象__dict__属性只存放对象的名称空间的数据。比如self.xx
3.类存在继承关系,父类的__dict__ 并不会影响子类的__dict__