Python: how to implement __getattr__()?

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

    Late to the party, but found two really good resources that explain this better (IMHO).

    As explained here, you should use self.__dict__ to access fields from within __getattr__, in order to avoid infinite recursion. The example provided is:

    def __getattr__(self, attrName):
      if not self.__dict__.has_key(attrName):
         value = self.fetchAttr(attrName)    # computes the value
         self.__dict__[attrName] = value
      return self.__dict__[attrName]
    

    Note: in the second line (above), a more Pythonic way would be (has_key apparently was even removed in Python 3):

    if attrName not in self.__dict__:
    

    The other resource explains that the __getattr__ is invoked only when the attribute is not found in the object, and that hasattr always returns True if there is an implementation for __getattr__. It provides the following example, to demonstrate:

    class Test(object):
        def __init__(self):
            self.a = 'a'
            self.b = 'b'
    
        def __getattr__(self, name):
            return 123456
    
    t = Test()
    print 'object variables: %r' % t.__dict__.keys()
    #=> object variables: ['a', 'b']
    print t.a
    #=> a
    print t.b
    #=> b
    print t.c
    #=> 123456
    print getattr(t, 'd')
    #=> 123456
    print hasattr(t, 'x')
    #=> True     
    

提交回复
热议问题