1.无处不在的__dict__
首先看下类的__dict__属性和类对象的__dict__属性,
class A(object):
"""
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(self):
print ('a static func.')
@classmethod
def class_test(self):
print ('a calss func.')
obj = A()
print (A.__dict__)
print (obj.__dict__)
运行结果如下:
{‘module’: ‘main’, ‘doc’: '\n Class A.\n ', ‘a’: 0, ‘b’: 1, ‘init’: <function A.init at 0x00000167D3C809D8>, ‘test’: <function A.test at 0x00000167D3C80D90>, ‘static_test’: <staticmethod object at 0x00000167D3C852E8>, ‘class_test’: <classmethod object at 0x00000167D3C85470>, ‘dict’: <attribute ‘dict’ of ‘A’ objects>, ‘weakref’: <attribute ‘weakref’ of ‘A’ objects>}
{‘a’: 2, ‘b’: 3}
由此可见,类的静态函数,类函数,普通函数,全局变量以及内置属性都放在类__dict__中,对象的__dict__中存储了self.xx的东西。
2.Python中常用的数据类型没有__dict__属性。
num = 3
ll = []
dd = {}
print num.__dict__
print ll.__dict__
print dd.__dict__
运行结果会报错。