How do you create an incremental ID in a Python Class
First, use Uppercase Names for Classes. lowercase names for attributes.
class Resource( object ):
class_counter= 0
def __init__(self, name, position, type, active):
self.name = name
self.position = position
self.type = type
self.active = active
self.id= Resource.class_counter
Resource.class_counter += 1
Trying the highest voted answer in python 3 you'll run into an error since .next()
has been removed.
Instead you could do the following:
import itertools
class BarFoo:
id_iter = itertools.count()
def __init__(self):
# Either:
self.id = next(BarFoo.id_iter)
# Or
self.id = next(self.id_iter)
...
Concise and elegant:
import itertools
class resource_cl():
newid = itertools.count().next
def __init__(self):
self.id = resource_cl.newid()
...
Using count from itertools is great for this:
>>> import itertools
>>> counter = itertools.count()
>>> a = next(counter)
>>> print a
0
>>> print next(counter)
1
>>> print next(counter)
2
>>> class A(object):
... id_generator = itertools.count(100) # first generated is 100
... def __init__(self):
... self.id = next(self.id_generator)
>>> objs = [A(), A()]
>>> print objs[0].id, objs[1].id
100 101
>>> print next(counter) # each instance is independent
3
The same interface works if you later need to change how the values are generated, you just change the definition of id_generator
.