擅长:python、mysql、java
<p>下面是一种计算实例的方法,不需要子类共享相同的id/count。元类用于为每个类创建单独的id计数器。</p>
<p>对元类使用Python3语法。</p>
<pre><code>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)
</code></pre>