0

I am confused why this happens. I'm defining a class Myclass for testing.

class Myclass:
    l = []
    def method1(self):
        self.l.append("test")

>>>a = Myclass()
>>>a.l
[]
>>>a.method1()
>>>a.l
['test']
>>>b = Myclass()
>>>b.l
['test']

Why does this happen? Why isn't a new empty list initialized?

Then

class Myclass:
    l = "string1"
    def method1(self):
        self.l = "string2"

>>>a = Myclass()
>>>a.l
'string1'

>>>a.method1()
>>>a.l
'string2'

b = Myclass()
>>>b.l
'string1'

Why does this happen for mutable objects only?

SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
Aslam
  • 1
  • 1
  • Because only mutable objects can be changed in-place (or, to put it another way, because only mutable objects are mutable...) – jonrsharpe Apr 27 '15 at 15:41
  • And if you did `self.l = ['my_new_list']` in the first snippet, that wouldn't have affected the other instance either. – Daniel Roseman Apr 27 '15 at 15:57
  • @DanielRoseman ,where i did that? i just appended to `l`.But it affected the new instance.why ? – Aslam Apr 27 '15 at 16:32
  • You didn't do that. If you had, it wouldn't have affected it. The duplicate question explains exactly why. – Daniel Roseman Apr 27 '15 at 16:49

0 Answers0