[英]Best way to generate a consecutive id in Python
給定一個具有屬性self.id
的 class,我需要用一個從 0 開始的計數器填充該屬性,並且該 class 的所有對象在程序的單次運行期間都需要一個唯一的 ID。 最好/最pythonic的方法是什么? 目前我使用
def _get_id():
id_ = 0
while True:
yield id_
id_ += 1
get_id = _get_id()
這是在 class 之外定義的,並且
self.id = get_id.next()
在課堂上的__init__()
。 有一個更好的方法嗎? 發電機可以包含在class里面嗎?
使用itertools.count :
from itertools import count
class MyClass(object):
id_counter = count().next
def __init__(self):
self.id = self.id_counter()
為什么要使用迭代器/發生器? 他們做的工作,但是不是太過分了嗎? 什么錯了
class MyClass(object):
id_ctr = 0
def __init__(self):
self.id = MyClass.id_ctr
MyClass.id_ctr += 1
使用itertools.count :
from itertools import count
id_counter = count(start=1)
def get_id():
return next(id_counter)
first_id = get_id() # --> 1
second_id = get_id() # --> 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.