Recursion problem
Raymond Hettinger
python at rcn.com
Sun May 19 03:57:49 EDT 2002
Hello Dennis,
I suspect that you want a separate data array for each instance of Compound.
Right now, both c and d share the same list. Separate them the way you did
with Simple. This should run nicely:
class Simple:
def __init__(self,x):
self.data = x
def getData(self):
return self.data
class Compound:
def __init__(self):
self.data = []
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)
print c.getData()
d = Compound()
d.data.append(c)
print d.getData()
Raymond Hettinger
"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 = []
> 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)
> print c.getData()
> d = Compound()
> d.data.append(c)
> print d.getData()
>
>
More information about the Python-list
mailing list