new to python question

The Geek theg33k at gmail.com
Wed Sep 28 23:06:23 CEST 2011


I'm clearly not understanding something about scope in python...  Any help
is appreciated

In the following script I'm attempting to create 2 Foo objects, for each Foo
object I create 2 Bars and add them to Foo's bar array

Something hokey is occurring with the "foo.bars.append(bar)" line such that
Foo.bars is treated as a "static" (I know python doesn't have statics)

I have a workaround using encapsulation for the bars array but I prefer
would also like to understand the issue.

TIA,
Brad

[SCRIPT]
foos = []

class Foo:
id = 0
bars = []

class Bar:
id = 0

for j in range(0, 2):
foo = Foo()

for i in range(0, 2):
bar = Bar()
bar.id = i
foo.bars.append(bar)
foos.append(foo)

for myFoo in foos:
print("foo id: ", myFoo.id)
for myBar in myFoo.bars:
print ("\tbar id: ", myBar.id)

[/SCRIPT]

[OUTPUT]
python test.py
foo id:  0
        bar id:  0
        bar id:  1
        bar id:  0
        bar id:  1
foo id:  0
        bar id:  0
        bar id:  1
        bar id:  0
        bar id:  1
[/OUTPUT]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110928/0d237d89/attachment.html>


More information about the Python-list mailing list