作用: 查看对象的属性,元类编程的时候有用。一般不自己写库基本上不会用到元类编程,__dict__的相对用途就小很多.
比如我有一个字典或者类,可以通过__dict__看其属性。
# -*- coding: utf-8 -*-
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__
运行结果:
{'a': 0, '__module__': '__main__', 'b': 1, 'class_test': <classmethod object at 0x00000000021882E8>, '__dict__': <attribute '__dict__' of 'A' objects>, '__init__': <function __init__ at 0x00000000023A5BA8>, 'test': <function test at 0x00000000023A5C18>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': '\n Class A.\n ', 'static_test': <staticmethod object at 0x00000000021881C8>}
{'a': 2, 'b': 3}
class request: # 声明request类 用于传递诊断请求
id = 0
type = None
data = []
def __init__(self, objDict):
self.id, self.type, self.data = objDict["id"], objDict["type"], objDict["data"]
test_data = [31.1555,4.2790,1.9467,0.6377,8.5239,201,36.6678,46.5123]#故障4数据**
tempReq = request({
"id": lineIndex,
"type": "pressureTransmitter",
"data": {
"pressureVals": test_data
},
})
print(tempReq.__dict__)
运行结果:
{'id': '123', 'type': 'pressureTransmitter', 'data': {'pressureVals': ['28.7568', '6.1312', '2.3456', '0.661', '12.3456', '284', '34.765', '46.69']}}
参考资料: