正如您在问题中所说,_id由父类和所有子类共享。为每个子类定义_id。from itertools import count
class Parent(object):
base_id = 0
_id = count(0)
def __init__(self):
self.id = self.base_id + self._id.next()
class Child1(Parent):
base_id = 100
_id = count(0) #
def __init__(self):
Parent.__init__(self)
print 'Child1:', self.id
class Child2(Parent):
base_id = 200
_id = count(0) #
def __init__(self):
Parent.__init__(self)
print 'Child2:', self.id
c1 = Child1() # 100
c2 = Child2() # 200
c1 = Child1() # 101
c2 = Child2() # 201
更新
使用元类:class IdGenerator(type):
def __new__(mcs, name, bases, attrs):
attrs['_id'] = count(0)
return type.__new__(mcs, name, bases, attrs)
class Parent(object):
__metaclass__ = IdGenerator
base_id = 0
def __init__(self):
self.id = self.base_id + next(self._id)