2015-12-14 99 views
0

我在类中定义了一个字典(我们称之为Thingy)。有时我需要使用其他Thingy实例作为thing1的字典中的键。但是,如果我尝试添加thing2作为值为1的关键字(比如说)到thing1的字典,那么thing2:1也会出现在thing2的字典中!使用对象作为键的奇怪Python字典行为

请确认您是否可以重现(蟒蛇2.7.6):

# class definition 
class Thingy: 
    def __init__(self, d={}): 
     self.dict = d 

# Test code 
thing1 = Thingy() 
thing2 = Thingy() 
thing1.dict[thing2] = 1 
print('Thing1.dict is {}'.format(thing1.dict)) 
print('Thing2.dict is {}'.format(thing2.dict)) 

给我

Thing1.dict is {<__main__.Thingy instance at 0x7f79fdeed998>: 1} 
Thing2.dict is {<__main__.Thingy instance at 0x7f79fdeed998>: 1} 

即使我从来没有改变过Thing2.dict!

回答

1

切勿使用可变对象作为默认参数:

class Thingy: 
    def __init__(self, d={}):