One int for each python object

Possible duplicate:
Auto-increment identifiers for class instances

I want something like the following Java class in Python:

public class MyObject { private static int ID = 0; private final int id; public MyObject() { id = ID++; } } 

In this Java code, each myObject will have an id , and there will be no way for two objects to have the same ID (this is a single-threaded application).

Is it possible to do something like this in Python?

+4
source share
3 answers

In Python, you can simply refer directly to a class attribute:

 class MyObject(object): ID = 0 def __init__(self): self.id = MyObject.ID = MyObject.ID + 1 

Demo:

 >>> class MyObject(object): ... ID = 0 ... def __init__(self): ... self.id = MyObject.ID = MyObject.ID + 1 ... >>> MyObject().id 1 >>> MyObject().id 2 >>> MyObject().id 3 >>> MyObject.ID 3 
+8
source

As I mentioned in my comment on @Martjin Pieters answer, id() inline can be good enough for your needs. id(obj) returns id for any object in the system that is unique during access (in fact, in some interpreters it is literally the memory address of the object). If your objects are not destroyed often, but your identifier links must remain valid even after destruction, id() should work for your unique needs.

From the docs:

[The value returned by id ()] is an integer (or long integer) that is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes can have the same id () value.

+2
source

@Martjin Pieters has the right idea, but I suggest itertools.count to itertools.count for this:

 class MyObject(object): ID = itertools.count() def __init__(self): self.id = MyObject.ID.next() >>> MyObject().id 0 >>> MyObject().id 1 >>> MyObject().id 2 >>> MyObject.ID count(3) 

Hope this helps

0
source

Source: https://habr.com/ru/post/1445635/


All Articles