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?