__setattr__ recursion problem
Hans Nowak
wurmy at earthlink.net
Thu Nov 29 12:43:24 EST 2001
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
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.
--Hans
More information about the Python-list
mailing list