计算一个类的实例?

时间:2011-12-25 03:55:14

标签: class python

我一直在清理我正在扩展的模块中的一些代码,我似乎无法找到Pythonify代码的方法:

global_next_id = 1

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

    global_next_id += 1

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

有人可以建议一种Python化此代码的方法吗?

7 个答案:

答案 0 :(得分:49)

尝试这样的事情:

from itertools import count

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

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

答案 1 :(得分:4)

这是一种计算没有后代类共享相同id / count的实例的方法。元类用于为每个类创建一个单独的id计数器。

对Metaclasses使用Python 3语法。

import itertools

class InstanceCounterMeta(type):
    """ Metaclass to make instance counter not share count with descendants
    """
    def __init__(cls, name, bases, attrs):
        super().__init__(name, bases, attrs)
        cls._ids = itertools.count(1)

class InstanceCounter(object, metaclass=InstanceCounterMeta):
    """ Mixin to add automatic ID generation
    """
    def __init__(self):
        self.id = next(self.__class__._ids)

答案 2 :(得分:4)

这应该做的工作:

class Obj:
    _counter = 0
    def __init__(self):
        Obj._counter += 1
        self.id = Obj._counter

答案 3 :(得分:2)

我找到了以下解决方案:

class Obj:
    counter = 0

    def __init__(self):
        type(self).counter += 1

    def __del__(self):
        type(self).counter -= 1

最好使用type(self).counter而不是Obj.counter

答案 4 :(得分:1)

发电机?

def get_next_id():
    curr_id = 1
    while True:
        yield curr_id
        curr_id += 1

答案 5 :(得分:0)

class InstanceCounter(object):
  # the instance counter
  counter = 0

  def __init__(self, val):
    self.val = all
    # incrementing every time an instance is created
    InstanceCounter.counter += 1

  def set_val(self, val):
    self.val = val

  def get_val(self, val):
    return self.val

  # accessing the instance counter should be done through a class method

  @classmethod
  def get_counter(cls):  
    return cls.counter

# See the instance counter as it increments as new instances are created
a=InstanceCounter(5)
print(a.get_counter())
b=InstanceCounter(7)
print(a.get_counter(), b.get_counter())
c=InstanceCounter(9)
print(a.get_counter(), b.get_counter(), c.get_counter())

答案 6 :(得分:-1)

Certificate (Invalid)