Search code examples
pythonoopcoding-stylegetattr

Use of __getattr__ in Python


How frequently should you use __getattr__ in Python, rather than normal methods?

Which of these would be considered better?

class A:
    def __getattr__(self, attribute):
        if attribute == "spam":
            return self._spam * 100
        elif attribute == "eggs":
            return "fried" + self._eggs
        raise AttributeError

or

class B:
    def get_spam(self):
        return self._spam * 100

    def get_eggs(self):
        return "fried" + self._eggs

Solution

  • Instead of __getattr__ or accessor methods, use the @property decorator:

    class B(object):
        @property
        def spam(self):
            return self._spam * 100
    
        @property
        def eggs(self):
            return "fried" + self._eggs
    

    Use __getattr__ only to support dynamic attributes, where the number and names of the attributes are not known at class definition time.