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...
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.
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.
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. (
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.
Concise and elegant:
import itertools class resource_cl(): newid = itertools.count().next def __init__(self): self.id = resource_cl.newid() ...
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) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With