Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create an incremental ID in a Python Class

Tags:

python

class

I would like to create a unique ID for each object I created - here's the class:

class resource_cl :     def __init__(self, Name, Position, Type, Active):         self.Name = Name         self.Position = Position         self.Type = Type         self.Active = Active 

I would like to have a self.ID that auto increments everytime I create a new reference to the class, such as:

resources = [] resources.append(resource_cl('Sam Sneed', 'Programmer', 'full time', True)) 

I know I can reference resource_cl, but I'm not sure how to proceed from there...

like image 214
meade Avatar asked Jun 25 '09 18:06

meade


People also ask

How do you create a unique ID in Python?

uuid1() is defined in UUID library and helps to generate the random id using MAC address and time component. bytes : Returns id in form of 16 byte string. int : Returns id in form of 128-bit integer. hex : Returns random id as 32 character hexadecimal string.

What is self ID in Python?

self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes.

What is id in Python class?

Python id() FunctionThe id() function returns a unique id for the specified object. All objects in Python has its own unique id. The id is assigned to the object when it is created. The id is the object's memory address, and will be different for each time you run the program. (

How do I find the data type of an object in Python?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.


Video Answer


2 Answers

Concise and elegant:

import itertools  class resource_cl():     newid = itertools.count().next     def __init__(self):         self.id = resource_cl.newid()         ... 
like image 79
Algorias Avatar answered Oct 09 '22 02:10

Algorias


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)         ... 
like image 34
foxyblue Avatar answered Oct 09 '22 01:10

foxyblue