All instances of a class have the same dict as an attribute in Python 3.2

99封情书 提交于 2019-11-29 18:06:02

They are refering to the same object. This is a very common gotcha. If you want them to each have their own dict, you need to have it created in the __init__ method.

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()

As your code currently stands, when you try to access stardict via self.stardict, python first looks for stardict on the instance, but when it doesn't find a stardict attribute there, it looks on the class. It finds stardict on the class, so it uses that. But, this implies that all instances find the same stardict (since they all instances of the same class) -- an update to one of their stardict and all of the others will know (faster than light speed!)*.

*Note that this doesn't voilate any laws of physics. Since they are the same object, there is no distance for the information to travel ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!