[英]Create an incremental ID in a Python class with subclasses each maintaining their own ID series
我想創建一個 class,其中 class 的每個 object 都被賦予一個從0
開始的唯一順序 ID。 我還希望每個子類都具有從0
開始的順序 ID,編號不受父類或兄弟類的影響。
使用類似問題的答案,我創建了 class Foo
class Foo:
id_iter = itertools.count()
def __init__(self):
self.id = next(self.id_iter)
Foo
的所有實例都將具有順序id
值。 我還想創建一個 class Bar
繼承自Foo
這樣
>>> Foo().id
0
>>> Foo().id
1
>>> Foo().id
2
>>> Bar().id # The first Bar id starts at 0 rather than 3
0
如果我像這樣創建Bar
:
class Bar(Foo):
def __init__(self):
super(Bar, self).__init__()
上面對Bar().id
的調用將返回3
,因為兩個類都使用相同的迭代器。 或者,我可以將id_iter = itertools.count()
添加回我的Bar
定義並獲得我期望的 output。 但是,我正在制作Foo
的多個子類,並且不想將該行添加到每個 class; 我希望Foo
的所有子類都自動繼承 ID 功能,而不必向子類定義添加任何額外內容。 我怎樣才能做到這一點?
您不能使用 class 屬性執行此操作,因為 class 屬性不會被繼承。 一種方法可能是使用單獨的字典來保持類的計數。 例如:
import itertools
class ClassCounter(object):
counters = {}
@classmethod
def get_counter(cls, class_to_count):
cls.counters.setdefault(class_to_count, itertools.count())
return next(cls.counters[class_to_count])
class Foo:
def __init__(self):
self.id = ClassCounter.get_counter(self.__class__)
class Bar(Foo):
def __init__(self):
super(Bar, self).__init__()
if __name__ == '__main__':
foo1 = Foo()
foo2 = Foo()
foo3 = Foo()
bar1 = Bar()
bar2 = Bar()
print(f"{foo1.id=}, {foo2.id=}, {foo3.id=}, {bar1.id=}, {bar2.id=}")
這應該打印:
foo1.id=0, foo2.id=1, foo3.id=2, bar1.id=0, bar2.id=1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.