__getattr__ weirdness
Stephan Diehl
stephan.diehl at gmx.net
Fri Aug 22 14:48:49 EDT 2003
Greg Brunet wrote:
> In adding the ability to refer to field values using dbfFile.field
> notation, I learned how to use __getattr__ and __setattr__ . After some
> trial and error, I got it working. But as part of my trials, I added
> some print statements to debug stuff. The ones I added to __setattr__
> work as expected, but the one in __getattr__ seems to get called just
> under 1000 times for every __getattr__ call!
>
> Something is obviously not right here - but I'm at a loss to understand
> what's going on. I've pared down my code to still show it happening &
> included it below. If you run this program & pipe the output to a file,
> you'll get just under 14000 debug lines. Any ideas? Thanks!
>
Within the __getattr__ method, you can't just do normal attribute access as
this will trigger another call to __getattr__, so you where stuck in an
infinite loop.
try to access the required attribute directly from the __dict__
def __getattr__(self, key):
""" Return DBF record values by field name """
print "_ga: " + key
try:
# return self._rec[self._fldNames.index(key.upper())]
^^^^
return self.__dict__['_rec'][self._fldNames.index(key.upper())]
except:
raise AttributeError("Unknown Field: %s" % ( key ))
Hope that helps
Stephan
More information about the Python-list
mailing list