How To capture an id into an array..
Josiah Carlson
jcarlson at nospam.uci.edu
Sun Mar 28 21:17:07 EST 2004
BALAJI RAMAN wrote:
> Hello everybody!!!
>
> I'm pretty much new to this OOP...
>
> I have a problem..
>
> Here is a part of code that I'm writing
>
> class V(E):
> """ This is a variable for MPY"""
> def __init__(self):
> print id(self)
> check=[]
> check.append(id(self))
> self.val = None
>
> what I do is call say v1=V() so it means that v1 belongs to the
> variable class..
>
> Again if I call v2=V() so now v2 also belong to this class.. I want
> to keep a track of all the instances of this class.. and store their
> ids in an array..
>
> any help in this regards is appreciated...
The poor way of doing it is...
class V(E):
check = []
def __init__(self):
print id(self)
self.check.append(id(self))
self.val = None
The reason it is poor is because if an object is deleted, its id could
be reused.
Instead, you should use weak references. I've found the following to be
useful on occasion...
import weakref
class V(E):
check = {}
def __init__(self):
#create a weak reference to yourself
#place it in the __olist
self.check[id(self)] = weakref.ref(self)
def __del__(self):
del self.check[id(self)]
def __repr__(self):
return str(id(self))
def get_olist(self):
#this creates a hard reference to every object
return [o() for o in self.check.values() if o() is not None]
- Josiah
More information about the Python-list
mailing list