problems with __getattr__ & __setattr__
Michael Hudson
mwh21 at cam.ac.uk
Tue Nov 16 15:40:55 EST 1999
ScherBi at BAM.com writes:
> I am having trouble using __getattr__ and __setattr__ in some classes. I've
> boiled it down to the code below.
> It dumps core under 1.5.2 on Linux or WinNT.
>
> I think maybe it's looping, if so, how does one go about doing this?
> (I'm assuming it's clear enough what I'm trying to do.)
>
> If I comment out the __gettattr__ operation, it doesn't dump core. Instead
> I get an AttributeError: eggs raised at the 'self.eggs[key] = value' call in
> __setattr__. This is what leads me to belive there's something circular
> going on here.
>
>
> Thanks,
> Bill
>
> -------------------------------------------------------------
>
> class spam:
>
> def __init__(self):
> self.eggs = {}
Hint: what does this call?
> def __getattr__(self, key):
> try:
> return self.eggs[key]
> except:
> raise
>
> def __setattr__(self, key, value):
It calls this!
> try:
> self.eggs[key] = value
And this calls __getattr__ which looks for self.eggs, which calls
__getattr__, which looks for self.eggs, which calls __getattr__, which
looks for self.eggs, which calls __getattr__, which looks for
self.eggs, which calls __getattr__, which looks for self.eggs, which
calls __getattr__,
Segmentation fault (core dumped)
> return 0
> except:
> raise
>
>
>
> if __name__ == '__main__':
>
> s = spam()
> print 'instance of spam created.'
>
try
def __init__(self):
self.__dict__['eggs'] = {}
instead; also
def __getattr__(self, key):
try:
return self.__dict__["eggs"][key]
except:
raise
is probably safer. What are the try/catch for? They aren't doing
anything here!
__getattr__-and-__setattr__-are-so-much-fun-we-don't-mind-the-
performance-hit-ly y'rs - Michael
More information about the Python-list
mailing list