__setattr__ recursion problem

Joonas Paalasmaa joonas at olen.to
Thu Nov 29 16:19:24 EST 2001


Hans Nowak wrote:
> 
> Joonas Paalasmaa wrote:
> >
> > The code above causes an infinite loop. How can I set an attribute of
> > Class
> > without overloading the __setattr__ function? Or does someone have some
> > other
> > solution to make that script work?
> >
> > class Class2:
> >         eggs = 1
> >         spam = 2
> >
> > class Class:
> >         base = Class2()
> >         def __setattr__(s,attr, value):
> >                 if hasattr(s.base, attr):
> >                         setattr(s.base, attr, value)
> >                 else:
> >                         setattr(s, attr, value)
> >
> > Class().foo = "eggs"
> 
> The short answer is that setattr(s, ...) calls s.__setattr__.
> Which calls setattr again, and so on.
> 
> This code strikes me as curious though, and I wonder why you
> would want to write it like this. The default idiom for a class
> and its subclass would be something like

Actually I am not trying to subclass the class. I am writing an
extension
object for VPython and I have to pass all the set/getattrs to an VPython
instance.
> class Class2:
>     def __init__(self):
>         self.eggs = 1
>         self.spam = 2
> 
> class Class(Class2):
>     pass
> 
> In your approach,
> 
> > class Class:
> >         base = Class2()
> 
> creates an instance of Class2 *that is shared by all instances
> of class*. I'm not sure if this is intentional, but I haven't seen
> people use this a lot. Maybe it's possible to rewrite this code
> without the setattr and the shared base.

That's true. I was just too lazy to write a __init__ in that example.



More information about the Python-list mailing list