1

Below is the documented way to create a mutable non-static class variable in python.

class Cla:

    def __init__(self):
        self.arr = []


    def showIds(self):
        print(str(id(self.arr)))


    def show(self):
        print(self.arr)


a = Cla()
b = Cla()
a.showIds()
b.showIds()

a.arr.append(10)
b.arr.append(20)
a.show()
b.show()

And it works (Sample output ...)

140174126200712
140174126185032
[10]
[20]

However, to accept some arguments while creating, I modified the __init__ to below. (Only change is in the __init__ function.

class Cla:

    def __init__(self, arr=[]):
        self.arr = arr


    def showIds(self):
        print(str(id(self.arr)))


    def show(self):
        print(self.arr)


a = Cla()
b = Cla()
a.showIds()
b.showIds()

a.arr.append(10)
b.arr.append(20)
a.show()
b.show()

And suddenly the list becomes shared.

140711339502152
140711339502152
[10, 20]
[10, 20]

My question is why? What is wrong with above approach.

PS: I have gone through below already.

Static class variables in Python -- Lists & Objects

How to avoid having class data shared among instances?

Krishna
  • 924
  • 1
  • 7
  • 28

0 Answers0