我想知道有没有办法在 python 中创建一个悬空指针?我想我们必须手动删除一个对象,然后该对象的引用将指向一个对程序没有意义的位置。我在这里找到了这个例子
import weakref
class Object:
pass
o = Object() #new instance
print ("o id is:",id(o))
r = weakref.ref(o)
print ("r id is:",id(r))
o2 = r()
print ("o2 id is:",id(o2))
print ("r() id is:",id(r()))
print (o is o2)
del o,o2
print (r(),r) #If the referent no longer exists, calling the reference object returns None
o = r() # r is a weak reference object
if o is None:
# referent has been garbage collected
print ("Object has been deallocated; can't frobnicate.")
else:
print ("Object is still live!")
o.do_something_useful()
在这个例子中,哪一个是悬空指针/引用?是 o 还是 r?我很困惑。是否也可以在堆栈中创建悬空指针?如果你愿意,给我一些简单的例子,这样我就可以理解它是怎么回事。提前致谢。