标签:
python 中__getattr__ 以及 __setattr__
下面是mydict.py:
#!/usr/bin/env python class Dict(dict): def __init__(self, **kw): super(Dict, self).__init__(**kw) def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(r"‘Dict‘ object has no attribute ‘%s‘" % key) def __setattr__(self, key, value): self[key] = value d = Dict(a=1, b=2) print d[‘a‘] # use __getattr__ function print d.a print d.b # use __setattr__ function d.b = 3 print d.b #print d.c class Test(): def __getattr__(self, a): return a t = Test() print t.ni
结果为:
1 1 2 3 ni
运行单元测试:
import unittest from mydict import Dict class TestDict(unittest.TestCase): def setUp(self): print(‘setUp...‘) def tearDown(self): print(‘tearDown...‘) def test_init(self): d = Dict(a=1, b=‘test‘) self.assertEqual(d.a, 1) self.assertEqual(d.b, ‘test‘) self.assertTrue(isinstance(d, dict)) def test_key(self): d = Dict() d[‘key‘] = ‘value‘ self.assertEqual(d.key, ‘value‘) def test_attr(self): d = Dict() d.key = ‘value‘ self.assertTrue(‘key‘ in d) self.assertEqual(d[‘key‘], ‘value‘) def test_keyerror(self): d = Dict() with self.assertRaises(KeyError): value = d[‘empty‘] def test_attrerror(self): d = Dict() with self.assertRaises(AttributeError): value = d.empty if __name__ == ‘__main__‘: unittest.main()
参考文档:http://www.liaoxuefeng.com/
python 中__getattr__ 以及 __setattr__
标签:
原文地址:http://www.cnblogs.com/xurui/p/getattr_add_setattr_in_python.html