Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

How to create an infinite sequence of ids in python?

"""
We have a Student class. Every
student has a name and an id.
The catch is that a student id is 
automatically set to next available one.
"""
from itertools import count

class Student:
    # id generator starting from 1
    student_id_generator = count(1)  # first_id=1

    def __init__(self, name):
        self.name = name
        # Generate next student's id
        self.id = next(Student.student_id_generator)

student1 = Student("Wissam")
student2 = Student("Fawzi")
print(student1.id)  # 1
print(student2.id)  # 2
 
PREVIOUS NEXT
Tagged: #How #create #infinite #sequence #ids
ADD COMMENT
Topic
Name
5+2 =