以下,base_id
和_id
是一个类变量,并在所有子类中共享。
有没有办法将他们分成每个班级?覆盖python中的类变量?
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
def __init__(self):
Parent.__init__(self)
print 'Child1:', self.id
class Child2(Parent):
base_id = 200
def __init__(self):
Parent.__init__(self)
print 'Child2:', self.id
c1 = Child1() # 100
c2 = Child2() # 201 <- want this to be 200
c1 = Child1() # 102 <- want this to be 101
c2 = Child2() # 203 <- want this to be 201
为什么要百位数字代表班级,有什么特别的理由吗?如果你得到100多个实例呢?那么你会有重叠。你会在哪里看到ID,并且有没有比使用ID更好地区分类的方法? (也许你可以显示一些额外的信息,例如。) – jpmc26
这实际上并不重要;即使eugene将ID改为2元组(例如(1,0),(1,1),(1,2)...代表'Child1'),创建独立计数器的问题仍然存在。 –