Python没有静态类型检测机制, 编译器不能保证程序一定会在运行的时候正确执行, 需要通过一些测试确保所写的函数能正确运行, 使用python内置的unittest模块进行, 参考以下代码以作备忘。
import unittest class Dict(dict): def __init__(self, **kw): super().__init__(**kw) def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError("Dict object has no attribute {0}".format(key)) def __setattr__(self, key, value): self[key]=value class TestDict(unittest.TestCase): 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()
参考 链接