Auto-incrementing IDs for Class Instances

孤街浪徒 提交于 2019-12-01 12:12:22

You can still use self to get at the _ID.

self.id = self._ID 
self.__class__._ID += 1

If you're using CPython, you can have a lazy man's ID:

class Edge(object):
    @property
    def id(self): return id(self)

Your edited code is treating _ID as though it were a instance variable, not a class variable. Based on Matt Joiner's answer what I think you mean is this:

class Edge:
    _ID = 0
    def __init__(self, u, v, w, c,f=0):
        self.id = self._ID; self.__class__._ID += 1
        self.src = u
        self.dest = v
        self.weight = w
        self.capacity = c
        self.flow = f

When I run your examples with this definition of Edge, I get:

>>> e = Edge(1,3,5,10,0)
>>> e.id
0
>>> Edge._ID
1
>>> f = Edge(2,3,5,10,0)
>>> f.id
1
>>> Edge._ID
2

Which is the desired result. However, others have pointed out that your original code worked for them, just like this code works for me, so I suspect the real problem is somewhere else in your code.

Before instantiating any Edge, you could set the class variable explicitly to 0 like so:

Edge._ID = 0
e = Edge(1,3,5,10,0)
f = Edge(2,3,4,5,0)

And the id's will be properly set.

While the other answers offered are answer the asked question (which is why I am not unaccepting the one I originally accepted), the correct way to do this would be to use itertools.count as follows:

class Edge:
    _ID = itertools.count()
def __init__(self, u, v, w, c,f=0):
    self.id = self._ID.next()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!