Python中的类变量[set()]

时间:2012-10-21 22:47:39

标签: python

为什么set的行为与python中类变量的字典不同。例如,

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

感谢您的帮助:)

编辑:我还注意到,如果在 init ()中定义self.x = set(),则可以避免添加到两个实例的问题。 删除拼写错误

1 个答案:

答案 0 :(得分:5)

不,你错了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})

实际上,在你的代码中你没有改变实例变量,你正在改变类变量:

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

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

你需要在这里使用实例变量:

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}, {})