计数类的实例? [英] Counting instances of a class?

查看:115
本文介绍了计数类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个模块中清理了一些代码,我正在扩展,我似乎没有找到一种方法来Pythonify这个代码:

I've been cleaning up some code from a module I'm extending and I can't seem to find a way to Pythonify this code:

global_next_id = 1

class Obj:
  def __init__(self):
    global global_next_id
    self.id = global_next_id

    global_next_id += 1

此代码使用全局ID来跟踪class(我需要内部的变量 self.id ,它需要是一个数字)。

This code uses a global id to keep track of instances of a class (I need the variable self.id internally as well, and it needs to be a number).

推荐答案

尝试这样:

from itertools import count

class Obj(object):
  _ids = count(0)

  def __init__(self):
    self.id = self._ids.next()

这篇关于计数类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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