This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: List member inside a class is shared by all instances of the class
Type: Stage:
Components: Interpreter Core Versions: Python 2.4, Python 2.3, Python 2.5
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: christian.heimes, glubglub, quentin.gallet-gilles
Priority: normal Keywords:

Created on 2007-11-13 12:53 by glubglub, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (3)
msg57449 - (view) Author: (glubglub) Date: 2007-11-13 12:53
In the class below, 'arr' list should be unique for each instance of
class Blah. In reality, 'arr' is shared by all instances of 'Blah'

class Blah:
	arr = []    # this member should not be 
                    #   shared across all instances of blah
	s = ''

	def __init__(self, s):
		self.s = s

	def __str__( self):
		return '[%s, %s]' % (self.s, str(self.arr))

objs = []
objs.append(Blah('obj-a'))
objs.append(Blah('obj-b'))
objs.append(Blah('obj-c'))

# add to first object's array
objs[0].arr.append('abc')

# bug: 'abc' got added to all arrays
# print all arrays
for obj in objs:
	print obj

------------------------------
Actual Output:
[obj-a, ['abc']]
[obj-b, ['abc']]
[obj-c, ['abc']]

Expected Output:
[obj-a, ['abc']]
[obj-b, []]
[obj-c, []]
msg57450 - (view) Author: Quentin Gallet-Gilles (quentin.gallet-gilles) Date: 2007-11-13 13:11
That's the expected behavior, actually. The variables 'arr' and 's' are
static variables in the class Blah.
This is discussed in several places in the doc and the FAQ, e.g.
http://www.python.org/doc/faq/programming/#how-do-i-create-static-class-data-and-static-class-methods


What you're looking for is :

class Blah:
    def __init__(self, s):
        self.arr= []
        self.s = s
...
msg57451 - (view) Author: Christian Heimes (christian.heimes) * (Python committer) Date: 2007-11-13 14:13
It's a known feature - and a known gotcha for new Python developers.
History
Date User Action Args
2022-04-11 14:56:28adminsetgithub: 45778
2007-11-13 14:13:57christian.heimessetstatus: open -> closed
resolution: not a bug
messages: + msg57451
nosy: + christian.heimes
2007-11-13 13:11:41quentin.gallet-gillessetnosy: + quentin.gallet-gilles
messages: + msg57450
2007-11-13 12:53:38glubglubcreate