python - How to avoid having class data shared among instances? -


what want behavior:

class a:     list=[]  y=a() x=a()   x.list.append(1) y.list.append(2) x.list.append(3) y.list.append(4)  print x.list     [1,3] print y.list     [2,4] 

of course, happens when print is:

print x.list     [1,2,3,4] print y.list     [1,2,3,4] 

clearly sharing data in class a. how separate instances achieve behavior desire?

you want this:

class a:     def __init__(self):         self.list = [] 

declaring variables inside class declaration makes them "class" members , not instance members. declaring them inside __init__ method makes sure new instance of members created alongside every new instance of object, behavior you're looking for.


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -