Need to pass Object by value into a list

Fredrik Lundh fredrik at pythonware.com
Mon Sep 26 13:29:00 EDT 2005


Aaron wrote:

> I have a data sructure setup and I populate it in a loop like so:
>
> y=0
> while X:
>    DS.name = "ASDF"
>    DS.ID = 1234
>
>    list[y] = DS;
>    y = y + 1
>
> print list
>
> This does not work because DS is passed in by reference causing all
> entries into the list to change to the most current value.  I cannot
> find a "new" function in Python like there is in C++.  How do you do
> this in Python?

I assume DS is a class?

to create an instance of a class, call the class object:

L = []

while X:
    ds = DS()
    ds.name = "ASDF"
    ds.id = 1234
    L.append(ds)

spending some time with the tutorial might help:

    http://docs.python.org/tut/tut.html

(lists are described in chapter 3, classes in chapter 9)

</F>






More information about the Python-list mailing list