Counting instances of a class?

后端 未结 7 1496
失恋的感觉
失恋的感觉 2020-11-29 04:19

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 __         


        
7条回答
  •  执笔经年
    2020-11-29 04:48

    Here is a way to count instances without descendant classes sharing the same id/count. A metaclass is used to create a separate id counter for each class.

    Uses Python 3 syntax for Metaclasses.

    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)
    

提交回复
热议问题