Recursion problem

Dennis Peterson denpeterson at yahoo.com
Sun May 19 13:44:30 EDT 2002


umm...unless  you declare it static, of course...

"Dennis Peterson" <denpeterson at yahoo.com> wrote in message
news:ac8bot01515 at enews1.newsguy.com...
> Thanks for the help, John, I'll follow your advice. All the oop I've done
> until now was C++, which has no class-level data, and thinking in those
> terms made this seem very strange.
> -Dennis
>
> "John Machin" <sjmachin at lexicon.net> wrote in message
> news:c76ff6fc.0205190444.204fd65e at posting.google.com...
> > "Dennis Peterson" <denpeterson at yahoo.com> wrote in message
> news:<ac7d2u02vgg at enews2.newsguy.com>...
> > > I'm trying to implement a basic Composite pattern. In the following
> code, I
> > > expect c.getData() and d.getData() to both return "hellogoodbye".
> Instead,
> > > on d.getData() I get stacktrace printing "y += i.getData()" repeatedly
> until
> > > recursion depth exceeded. Why?
> > >
> > > I'm new to Python, running latest Windows version just downloaded.
> > >
> > > class Simple:
> > >     def __init__(self,x):
> > >         self.data = x
> > >     def getData(self):
> > >         return self.data
> > >
> > > class Compound:
> > >     data = []
> >
> > This "data" is a *CLASS*-level attribute, shared by all instances of
> > the class.
> > You should have an __init__() similar to the other class, to set
> > self.data to [].
> >
> > >     def getData(self):
> > >         y = ""
> > >         for i in self.data:
> > >             y += i.getData()
> > >         return y
> > >
> > > def test():
> > >     a = Simple("hello")
> > >     b = Simple("goodbye")
> > >     c = Compound()
> > >     c.data.append(a)
> > >     c.data.append(b)
> >
> > Insert a print statement here ... print c.data
> > >     print c.getData()
> > >     d = Compound()
> > >     d.data.append(c)
> >
> > Now for the big surprise:
> >       print d.data
> > *AND*
> >       print c.data
> > Just like the man said, c.data and d.data are the same thing ... and
> > uh-oh, that means c contains a reference to itself!
> > >     print d.getData()
> >
> > d contains c, which contains c, so you start emulating the mythical
> > ooloo bird, until saved by the recursion limit.
> >
> > *HINT* Unless you expect your code to work correctly first time or if
> > not that kind strangers will always do your debugging for you, learn
> > to put in print statements to give yourself a bit of a clue as to what
> > is going wrong. You seem to have jumped right in to the OO aspects of
> > Puthon; perhaps you might like to write yourself a mixin class that
> > supplies a generic dump() method for debugging instances of classes
> > that inherit from it.
>
>





More information about the Python-list mailing list