On 23/10/2011 01:26, Gnarlodious wrote:
Say this:
class tester():
_someList = [0, 1]
def __call__(self):
someList = self._someList
someList += "X"
return someList
test = tester()
But guess what, every call adds to the variable that I am trying to
copy each time:
test()
[0, 1, 'X']
test()
[0, 1, 'X', 'X']
Can someone explain this behavior? And how to prevent a classwide
constant from ever getting changed?
'_someList' is part of the class itself.
This:
someList = self._someList
just creates a new _reference to the list and this:
someList += "X"
appends the items of the sequence "X" to the list.
Note that a string is also a sequence of characters, so:
>>> x = []
>>> x += "XY"
>>> x
['X', 'Y']
Python will copy something only when you tell it to copy. A simple way
of copying a list is to slice it:
someList = self._someList[:]
--
http://mail.python.org/mailman/listinfo/python-list