Python: how to implement __getattr__()?

后端 未结 8 1841
北海茫月
北海茫月 2020-12-07 22:57

My class has a dict, for example:

class MyClass(object):
    def __init__(self):
        self.data = {\'a\': \'v1\', \'b\': \'v2\'}

Then I

8条回答
  •  醉梦人生
    2020-12-07 23:19

    I like to take this therefore.

    I took it from somewhere, but I don't remember where.

    class A(dict):
        def __init__(self, *a, **k):
            super(A, self).__init__(*a, **k)
            self.__dict__ = self
    

    This makes the __dict__ of the object the same as itself, so that attribute and item access map to the same dict:

    a = A()
    a['a'] = 2
    a.b = 5
    print a.a, a['b'] # prints 2 5
    

提交回复
热议问题