这或多或少是我跟踪类实例数量的方式,因为每次创建一个实例时都会调用 __new__
:
class MyClass():
def __new__(klass):
try:
klass.__instances = klass.__instances + 1
except NameError:
klass.__instances = 1
return super(MyClass,klass).__new__(klass)
当对类的特定实例进行新引用时,是否有一个神奇的方法被调用?如果没有,是否有一种直接的方法来实现?例如:
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.")
现在:
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
编辑:
Here's the problem我想我会尝试使用引用跟踪来解决。
我的想法是拥有一个对象A
实例,其中包含对对象B
的多个(弱)引用。有一个单独的列表,其中包含所有有效的 B
。还有所有 A
的列表(数千个)。理想的行为是,当从 B
列表中删除任何一个 B
时,任何对象 A
都将变为 None
如果它包含对从 B
列表中删除的特定 B
的引用。
最佳答案
据我所知,没有什么神奇的方法可以做到这一点,但也许你可以使用 sys.getrefcount()
:
Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to
getrefcount()
.
使用您的示例:
>>> import sys
>>> class MyClass: pass
...
>>> L1 = []
>>> L2 = []
>>> L1.append(MyClass())
>>> sys.getrefcount(L1[0])
2
>>> L2.append(L1[0])
>>> sys.getrefcount(L1[0])
3
>>> del L1[0]
>>> sys.getrefcount(L2[0])
2
关于python - 跟踪对对象实例的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27053928/