new to python question

Benjamin Kaplan benjamin.kaplan at case.edu
Wed Sep 28 17:12:13 EDT 2011


On Wed, Sep 28, 2011 at 5:06 PM, The Geek <theg33k at gmail.com> wrote:
> 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]


It's a pretty common gotcha for people coming from other languages.
Everything declared in the class scope becomes an attribute of the
class.
>>> class Foo(object) :
...    a = 3
...    def b() : pass
...
>>> dir(Foo)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__', 'a', 'b']

Mutating those objects mutates the attribute of the class, which is
visible to all instances of the class.

In order to get an instance of a class, you have to add the field to
the instance of the class instead of to the class itself.

class Bar(object) :
    def ___init__(self) :
        self.a = 3



More information about the Python-list mailing list