This is more or less how I would track the number of class instances, since __new__
is called every time one is made:
class MyClass():
def __new__(klass):
try:
klass.__instances = klass.__instances + 1
except NameError:
klass.__instances = 1
return super(MyClass,klass).__new__(klass)
Is there a magic method that is called when a new reference to a specific instance of a class is made? If not, is there a straight forward way to implement one? For example:
class MyClass():
def __init__(self):
self.__ref = 1
print(self,"created.")
def __new_reference(self):
self.__ref = self.__ref + 1
print("Reference to",self,"added.")
def __del_reference(self):
self.__ref = self.__ref - 1
print("Reference to",self,"deleted.")
So now:
L1 = []
L2 = []
L1.append(MyClass()) #<MyClass object> created
L1[0].__ref #1
L2.append(L1[0]) #Reference to <MyClass object> added.
L2[0].__ref #2
L1.pop(0) #Reference to <MyClass object> deleted.
L2[0].__ref #1
Edit:
Here's the problem I thought I would try to solve using reference tracking.
My idea is to have an object A
instance that contains multiple (weak) references to object B
s. There is a separate list containing all valid B
s. There is a list of all the A
s as well (thousands). The desired behavior is that when any one B
is removed from the B
list, for any object A
to become None
if it contained a reference to that particular B
removed from the B
list.