user1431282
user1431282

Reputation: 6835

Class Variable In Python [set()]

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

Upvotes: 0

Views: 157

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

No you're wrong both have the key:5:

In [56]: class Test1:
   ....:        x=set()
   ....:    y={}
   ....: 

In [57]: hamster=Test1()

In [58]: chinchilla=Test1()

In [59]: hamster.x.add('hi')  # now both sets in both instances have 'hi'

In [60]: hamster.y['key']=5

In [62]: hamster.x,chinchilla.x
Out[62]: (set(['hi']), set(['hi']))

In [63]: hamster.y,chinchilla.y
Out[63]: ({'key': 5}, {'key': 5})

Actually in your code you're not changing instance variable, you're changing class variables:

In [65]: Test1.x
Out[65]: set(['hi'])

In [66]: Test1.y
Out[66]: {'key': 5}

you need to use instance variables here:

In [71]: class Test1():
    def __init__(self):
        self.x=set()
        self.y={}
   ....:         
   ....:         

In [75]: hamster=Test1()

In [76]: chinchilla=Test1()

In [77]: hamster.x.add('hi')

In [78]: chinchilla.x.add('bye')

In [79]: hamster.x
Out[79]: set(['hi'])

In [81]: chinchilla.x
Out[81]: set(['bye'])


In [82]: hamster.y['key']=5

In [83]: hamster.y,chinchilla.y
Out[83]: ({'key': 5}, {})

Upvotes: 5

Related Questions