Python中的__dict__是什么,有啥用?

链接1把dict是什么说的很清楚了。

作用: 查看对象的属性,元类编程的时候有用。一般不自己写库基本上不会用到元类编程,__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']}}

参考资料: 

Python __dict__属性详解 - 星空·77 - 博客园

python中__dict__的作用是什么? - 知乎

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值