-1

I have implemented a simple lazy initialization in Python class:

class Base:
    def __init__(self):
        pass

    def __getattr__(self, item):
        print('__getattr__ was called!')

class Derived(Base):
    def GetValue(self):
        try:
            return self.val
        except AttributeError:
            self.val = 1
            return self.val

obj = Derived()
print(obj.GetValue())

I would like to catch an AttributeError when method GetValue() is called. In this example it doesn't happen, a method getattr is called. The method getattr() in Base class is mandatory and I cannot resign from using it. If it is possible I also don't want to resign of using try-except block. What could be a solution for this problem in Python 2.7?

Michal
  • 627
  • 3
  • 13

1 Answers1

1

If you cannot resign from using the __getattr__ method you have to manually throw the exception.

class Base:
    def __init__(self):
        pass

    def __getattr__(self, item):
        print('__getattr__ was called!')

        if not hasattr(self, item):
            raise AttributeError(self.__class__.__name__ +
                " instance has no attribute '" + item + "'")

class Derived(Base):
    def GetValue(self):
        try:
            return self.val
        except AttributeError:
            self.val = 1
            return self.val

obj = Derived()
print(obj.GetValue())
Praind
  • 1,551
  • 1
  • 12
  • 25