码迷,mamicode.com
首页 > 编程语言 > 详细

python 中__getattr__ 以及 __setattr__

时间:2016-05-16 01:57:52      阅读:378      评论:0      收藏:0      [点我收藏+]

标签:

 

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!