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

类的所有实例与python 3.2中的属性具有相同的dict,第1张

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

他们指的是同一个对象。这是一个非常常见的陷阱。如果希望它们每个都有自己的

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
属性时,它将在 class
上查找。它
stardict
在类上找到,因此使用它。但是,这意味着所有实例都找到相同的对象
stardict
(因为它们所有相同类的实例)-更新它们中的一个实例以及所有其他实例
stardict
都知道(快于光速!)*。

*请注意,这不会破坏任何物理定律。由于它们是同一对象,因此信息传播没有距离…



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5632455.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存