[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [pygame] Variables linking to eachother



Ok, I'm sure others are better qualified than I am to answer this, 
but here I go.

First of all, this is a basic python issue, not a pygame one.

Variables in python are simply names that have been bound to 
objects.  When you say a = b, you are simply binding another 
name to the object already pointed to by b.

>>> class foo:
...  pass
>>> a = foo()
>>> b = foo()
>>> a is b
0

>>> class foo:
...  pass
>>> a = foo()
>>> b = a
>>> a is b
1

With immutables (such as strings) this can look tricky:

>>> a = "X"
>>> b = "X"
>>> a is b
1

Since the string "X" can't be changed, all references to an 
"X" string point to the same copy.

Now, on to what was bothering you in your example:

> platformList.insert(1, eval( str(platformList[selectedPlatform])))

Let me restate this for you:

>>> selectedPlatform = 0
>>> a = foo()
>>> platformList = [a]
>>> platformList
[<__main__.foo instance at 0x8149044>]
>>> b = platformList[selectedPlatform]
>>> platformList.insert(0,b)
>>> platformList
[<__main__.foo instance at 0x8149044>, <__main__.foo instance at 0x8149044>]
>>> a is b
1
>>> platformList[0] is platformList[1]
1

All you're doing it pushing the same object around.  The eval() trick you 
played was one solution - a better one might have been to use a copy() 
method or create a new platform object, to ensure you are dealing with two 
unique objects.  

There are many ways around this "problem," but the best is to structure 
code in a pythonic way so these issues are less prone to occur. This 
only comes from practice and study.

Look here http://www.python.org/doc/current/tut/node11.html for more 
info - the python.org site is a wealth of information.


On Sun, 2003-03-23 at 05:08, campbell barton wrote:
> I have had this problem a few times.
> When I assign a variable, sometimes they 'link' to eachother eg
> 
> x = 1
> y = x
> x = 2
> print y
> 2
> 
> In this example of what is the problem is, however this example works.
> 
> I had the problem when duplicating an item in a list.
> platformList.insert(1, platformList[selectedPlatform]) # This had problems, both items linked togather and I could not change one part of the list item without the other changing too.
> 
> However turning the list item into a string and eval()'ing it worked without the linking problem.
> platformList.insert(1, eval( str(platformList[selectedPlatform])))
> 
> Does anyone know what is going on, how to get around this problem a better way?