Python: how to implement __getattr__()?

后端 未结 8 1911
北海茫月
北海茫月 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:10

    class A(object):
      def __init__(self):
         self.data = {'a': 'v1', 'b': 'v2'}
      def __getattr__(self, attr):
         try:
           return self.data[attr]
         except:
           return "not found"
    
    
    >>>a = A()
    >>>print a.a
    v1
    >>>print a.c
    not found
    

提交回复
热议问题