Is there any difference between this code, which uses dot notation for attribute access:
def get_foo(self):
try:
return self._attribute
except AttributeError:
self._attribute = 'something'
return self._attribute
And the following code, which uses the getattr
function:
def get_foo(self):
try:
return getattr(self, '_attribute')
except AttributeError:
self._attribute = 'something'
return self._attribute
They seem to behave the same way to me, but I came across the latter example in some code and I was curious why one would opt for calling getattr()
in this case.