Python:如何“杀死"类实例/对象? [英] Python: how to "kill" a class instance/object?

查看:69
本文介绍了Python:如何“杀死"类实例/对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望一个 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):

  1. 退出声明变量的代码块(第一次使用)
  2. 销毁对象将释放所有属性/方法变量的引用 -> 对象引用
  3. 调用del变量也会删除当前上下文中的引用
  1. exiting block of code where variable was declared (used for the first time)
  2. destructing object will release references of all attributes/method variable -> object references
  3. 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).

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆