-2

I have the following python code:

class C:
    b={}

c1=C()
c2=C()
c1.b[1]='s1'
c2.b[1]='s2'
print(c1.b[1])

I expected the output to be "s1" but it actually outputs "s2". Why and how can i get around this? Sorry i'm a complete newbie to python this is probably a trivial question....

curious
  • 1
  • 1
  • 1
    `b` is a *class attribute*, since you assigned it in the body of the class, and is therefore shared by all instances of the class. To make it an *instance attribute*, add a `__init__()` method to the class and assign `self.b = {}` there. – jasonharper Jan 03 '19 at 03:17

1 Answers1

2
class C:
    def __init__(self):
        self.b={}

c1=C()
c2=C()
c1.b[1]='s1'
c2.b[1]='s2'
print(c1.b[1]) #s1

You need to create an instance method def __init__(self): and put your dictionary into the instance level rather than at the class level.

ycx
  • 3,155
  • 3
  • 14
  • 26