0

为什么 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(),你可以避免添加到两个实例的问题。删除了错别字

4

1 回答 1

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}, {})
于 2012-10-21T22:56:03.590 回答