Why does set behave differently from a dictionary for class variables in python. For instance,
class Test1:
x=set()
y={}
hamster=Test1()
chinchilla=Test1()
hamster.x.add('hi') # now both sets in both instances have 'hi'
hamster.y['key']=5 # only the hamster instance will contain 5
Thanks for any help 🙂
EDIT: I also noticed that if you define self.x=set() in init(), you can avoid the issue of adding to both instances. Removed typos
No you’re wrong both have the
key:5:Actually in your code you’re not changing instance variable, you’re changing class variables:
you need to use instance variables here: