类的所有实例都与Python 3.2中的属性具有相同的dict

时间:2013-03-19 00:40:40

标签: python dictionary python-3.x instance

我正在用Python编写一个太空交易游戏,我已经决定将地图拆分成更小的块,以减少在任何给定时间需要考虑在屏幕上绘制的对象数量。

这是通过拥有一个Sector对象来处理的,该对象定义如下:

class Sector:
   x=0     #Position of the sector. The galactic (absolute) position of any object is its in-sector position
   y=0     #plus the galactic position offset times the size of a sector. 
   stardict=dict()

然后,生成器代码用75颗星填充每个扇区(目前其中100个扇区),保持标准。

thesector=Sector()

size=size/2

#Generate stars
for t in range(stars):
    #name="Star "+str(t)
    name=generate_name().capitalize()
    thesector.stardict[name]=Star( name, (random.randint(-size,size), random.randint(-size,size)), (random.randint(0,255), random.randint(0,255), random.randint(0,255)), random.randint(3,7))

    if math.floor((t/stars)*100)==(t/stars)*100: print("Generating stars: "+str((t/stars)*100)+"% done.")

然而,在尝试实际运行程序时有一些奇怪的错误,并且用调试器打开它会显示原因:每个扇区的stardict属性是相同的,它们每个都包含完全相同的星(不是重复的,它们都是相同的记忆地址)。据我所知,每个Sector.stardict实际上引用了相同的dict对象。

我不知道为什么会这样。任何人都可以对此有所了解吗?

1 个答案:

答案 0 :(得分:4)

他们指的是同一个对象。这是一个非常普遍的问题。如果您希望每个人都有自己的dict,则需要在__init__方法中创建它。

class Sector:
   x = 0     #Position of the sector. The galactic (absolute) position of any object is its in-sector position
   y = 0     #plus the galactic position offset times the size of a sector. 
   def __init__(self):
       self.stardict = dict()

正如您的代码目前所示,当您尝试通过stardict访问self.stardict时,python首先在实例上查找stardict,但是当它没有时在那里找不到stardict属性,它在上查找。它在类上找到stardict,因此它使用它。但是,这意味着所有实例都找到相同的stardict(因为它们是同一类的所有实例) - 对其中一个stardict的更新以及所有其他实例都知道(比光速更快) !)*。

*请注意,这并没有消除任何物理定律。因为它们是同一个物体,所以信息没有距离......