Python:如何“杀死"类实例/对象? [英] Python: how to "kill" a class instance/object?
问题描述
我希望一个 Roach 类在达到一定的饥饿"时死亡",但我不知道如何删除该实例.我的术语可能有误,但我的意思是我的窗户上有很多蟑螂",我希望特定的蟑螂完全消失.
I want a Roach class to "die" when it reaches a certain amount of "hunger", but I don't know how to delete the instance. I may be making a mistake with my terminology, but what I mean to say is that I have a ton of "roaches" on the window and I want specific ones to disappear entirely.
我会向您展示代码,但它很长.我将 Roach 类附加到 Mastermind 类蟑螂种群列表中.
I would show you the code, but it's quite long. I have the Roach class being appended into a Mastermind classes roach population list.
推荐答案
一般:
- 每个绑定变量 -> 对象都会增加内部对象的引用计数器
减少引用有几种常用的方法(取消引用对象->变量绑定):
- Each binding variable -> object increases internal object's reference counter
there are several usual ways to decrease reference (dereference object -> variable binding):
- 退出声明变量的代码块(第一次使用)
- 销毁对象将释放所有属性/方法变量的引用 -> 对象引用
- 调用
del变量
也会删除当前上下文中的引用
- exiting block of code where variable was declared (used for the first time)
- destructing object will release references of all attributes/method variable -> object references
- calling
del variable
will also delete reference in the current context
在删除对一个对象的所有引用(计数器== 0)后,它成为垃圾收集的良好候选者,但不能保证它会被处理(参考这里):
CPython 目前使用带有(可选)的引用计数方案延迟检测循环链接的垃圾,收集最多对象一旦变得不可访问,但不能保证收集包含循环引用的垃圾.查看文档gc 模块的有关控制收集的信息循环垃圾.其他实现的行为不同,CPython 可能改变.不要依赖对象的立即终结变得无法访问(例如:总是关闭文件).
CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the documentation of the gc module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable (ex: always close files).
对象上存在多少引用,使用sys.获取引用计数
用于配置/检查垃圾收集的模块是 gc一个>
module for configure/check garbage collection is gc
GC 将调用 object.__ del__销毁对象时的方法(额外参考这里)
GC will call object.__ del__ method when destroying object (additional reference here)
一些不可变对象(如字符串)以特殊方式处理 - 例如如果两个变量包含相同的字符串,则它们可能引用相同的对象,但有些不是 - 检查 识别对象,为什么id(...)的返回值会改变?
some immutable objects like strings are handled in a special way - e.g. if two vars contain same string, it is possible that they reference the same object, but some not - check identifying objects, why does the returned value from id(...) change?
对象的id可以通过内置函数找到id一个>
id of object can be found out with builtin function id
模块 memory_profiler 看起来很有趣 - 一个用于监控内存使用的模块一个python程序
module memory_profiler looks interesting - A module for monitoring memory usage of a python program
这个话题有很多有用的资源,一个例子:在python中查找对一个对象的所有引用
there is lot of useful resources for the topic, one example: Find all references to an object in python
这篇关于Python:如何“杀死"类实例/对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!