problems with __getattr__ & __setattr__
ScherBi at BAM.com
ScherBi at BAM.com
Tue Nov 16 16:01:01 EST 1999
Michael Hudson wrote:
> 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!
Thanks. I came upon your this solution in the interval.
The try/except were not relevent in the sample, but are in my real code.
sorry. 8-)
> __getattr__-and-__setattr__-are-so-much-fun-we-don't-mind-the-
> performance-hit-ly y'rs - Michael
Yes, I had to convince a colleague (it wasn't hard) that the syntactic sugar
they produce are worth the __dict__ mangling ugliness. :)
Thanks again.
Bill
> -----Original Message-----
> From: Michael Hudson [mailto:mwh21 at cam.ac.uk]
> Sent: Tuesday, November 16, 1999 3:41 PM
> To: python-list at python.org
> Subject: Re: problems with __getattr__ & __setattr__
>
>
> 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
>
> --
> http://www.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list