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: bug in classlevel variabels
Type: Stage:
Components: Interpreter Core Versions: Python 2.4
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: georg.brandl, thomasda
Priority: normal Keywords:

Created on 2006-08-30 18:44 by thomasda, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg29711 - (view) Author: Thomas Dybdahl Ahle (thomasda) Date: 2006-08-30 18:44
class A:
    js = []
    
    def add (self, j):
        self.js.append(j)

    def clone (self):
        c = A()
        for j in self.js:
            c.add(j)
        return c

a = A()
b = a.clone()
b.add(3)

print a.js
print b.js

The above code should print "[]\n[3]", but instead it
prints "[3]\n[3]"!

It works as expected, if you change "js = []" to "def
__init__ (self):
        self.js = []"
msg29712 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2006-08-30 19:28
Logged In: YES 
user_id=849994

This is not a bug. The "js" list exists in the class's
namespace and exists only once, and if you don't rebind the
name, "self.js" always refers to this. Therefore it is
shared between instances.
History
Date User Action Args
2022-04-11 14:56:19adminsetgithub: 43914
2006-08-30 18:44:30thomasdacreate