Python:有没有办法知道类的实例是否已分配给变量?
我正在编写一个 Body2D 类,在 __add__() 魔术方法下,我希望能够知道该类的实例是否实际分配给变量,或者是否只是为了添加。
例如,我如何能够区分以下两者之间的区别:
earth = Body2D()
venus = Body2D()
mars = earth + venus
...其中两个第一个实例都绑定到变量,而这:
mars = Body2D() + Body2D()
?
我问的原因是因为我已经创建了一个类变量(一个列表),其中包含迄今为止创建的所有对象的ID,并且我不想存储尚未分配给变量的主体的ID。
任何帮助将不胜感激!谢谢!
I am writing a Body2D class, and under the __add__()
magic method I would like to be able to know whether an instance of the class is actually assigned to a variable, or whether it was created just for the addition.
For example, how would I be able to tell the difference between this:
earth = Body2D()
venus = Body2D()
mars = earth + venus
... where both first instances are tied to a variable, and this:
mars = Body2D() + Body2D()
?
The reason I ask is because I have created a class variable (a list) of all the IDs of the objects created so far, and I don't want to store IDs of bodies that have not been assigned to variables.
Any help would be much appreciated! Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是不可能的。从类实例的角度来看,除了引用计数未能减少之外,在赋值时没有任何变化,因为引用计数在加载时会增加入栈;从堆栈中弹出并存储到变量将所有权转移给变量,仅此而已。这不是 C++,其中赋值涉及调用构造函数或赋值运算符来执行自定义代码;在一般情况下,临时创建对象和为命名变量中的长期存储创建对象之间存在零实例可观察到的差异。
我怀疑这里有XY问题,并且很可能你真正的解决方案最终会使用weakref 模块以某种方式跟踪哪些对象仍然被引用(不保留一个参考你自己,这会阻止物体被清理)。
This isn't possible. From the perspective of your class instances, nothing changes at the moment of assignment aside from their reference count failing to be decremented, since the reference count is incremented when they're loaded onto the stack; popping from the stack to store to a variable transfers ownership to the variable, that's all. This isn't C++ where assignment involves constructor or assignment operators being invoked to execute custom code; in the general case, there is zero instance observable difference between creating an object temporarily and creating it for longer term storage in a named variable.
I suspect an XY problem here, and in all likelihood your true solution will end up using the
weakref
module in some way to track which objects remain referenced (without holding a reference yourself that would prevent the objects from being cleaned up).