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: error whit dict working whith class
Type: Stage:
Components: None Versions: Python 2.3
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: georg.brandl, st2015
Priority: normal Keywords:

Created on 2005-06-28 19:47 by st2015, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (4)
msg25663 - (view) Author: ST2015 (st2015) Date: 2005-06-28 19:47
se follow code:
"""
class my_class:
    a={}

    def __init__(self, n):
        self.a = n

    def hola(self, b):
        self.a["a"] = b

a1 = my_class({"a":1, "b":1})
print "a1=", a1.a
a2 = my_class({"a":1, "b":1})
a1.hola(2)
print "a2=", a2.a
print "a1=", a1.a
"""
must show:
a1= {'a': 1, 'b': 1}
a2= {'a': 1, 'b': 1}
a1= {'a': 2, 'b': 1}

but show:
a1= {'a': 1, 'b': 1}
a2= {'a': 2, 'b': 1}
a1= {'a': 2, 'b': 1}

This error happend only whit dicts, y only when de dict
atributte is defined before of the __init__ of the class

msg25664 - (view) Author: ST2015 (st2015) Date: 2005-06-28 19:54
Logged In: YES 
user_id=1304338

sorry the code is the folowing:
class my_class:
    a={}

    def __init__(self, n):
        for i in n:
            self.a[i] = n[i]
  
    def hola(self, b):
        self.a["a"] = b

a1 = my_class({"a":1, "b":1})
print "a1=", a1.a
a2 = my_class({"a":1, "b":1})
a1.hola(2)
print "a2=", a2.a
print "a1=", a1.a
msg25665 - (view) Author: ST2015 (st2015) Date: 2005-06-28 19:54
Logged In: YES 
user_id=1304338

sorry the code is the folowing:
class my_class:
    a={}

    def __init__(self, n):
        for i in n:
            self.a[i] = n[i]
  
    def hola(self, b):
        self.a["a"] = b

a1 = my_class({"a":1, "b":1})
print "a1=", a1.a
a2 = my_class({"a":1, "b":1})
a1.hola(2)
print "a2=", a2.a
print "a1=", a1.a
msg25666 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2005-06-28 20:01
Logged In: YES 
user_id=1188172

Then this is no bug.

You are never assigning to self.a, thus the "a" you
reference in the class's methods is the one defined as a
class attribute and therefore shared between instances.
History
Date User Action Args
2022-04-11 14:56:12adminsetgithub: 42136
2005-06-28 19:47:14st2015create