Just change:
return self.__dict__["m_%s" % name]
to:
return getattr(self, "m_%s" % name)
The former is using implementation details that don't apply, the latter is explicitly looking up a new attribute by name.
Note: For this specific case, I'd avoid __getattr__
entirely as involving too much overhead, and just do:
@property
def A(self):
return self.m_A
That will behave the same, and run faster (generic dispatch through __getattr__
and a getattr
call is more expensive than targeted lookup through a property descriptor). If you have a dozen such slots to make read-only accessors for, you can still use this pattern fairly cheaply by adding the accessors after making the class:
from operator import attrgetter
class Foo(object):
__slots__ = 'm_XXX', 'm_YYY', etc.
... rest of class body ...
# Add readonly accessors sans m_ prefix for each slot with an m_ prefix:
for membername in Foo.__slots__:
if membername.startswith('m_'):
setattr(Foo, membername.replace('m_', '', 1), property(attrgetter(membername)))