[英]How to make all the reference variables None in Python?
I got a typical ListNode class something like below,我得到了一个典型的 ListNode 类,如下所示,
class ListNode:
def __init__(self,val, next = None):
self.val = val
self.next = next
I created two instances of this class, and assigned one of the object to a variable called next in first instance as below,我创建了这个类的两个实例,并将其中一个对象分配给第一个实例中名为 next 的变量,如下所示,
node = ListNode(1)
next_node = ListNode(2)
node.next = next_node
However, if I assign nnode = None
, the node.next
still points to the instance next_node
and is not None
.但是,如果我分配nnode = None
,则node.next
仍然指向实例next_node
而不是None
。
print( next_node == node.next) # Prints True
next_node = None
print( node.next.val) # Prints 1
How can I make all the reference variables (eg node.next
in above case) make None without explicitly assigning them to None?我怎样才能让所有的参考变量(例如上面例子中的node.next
)在没有明确分配给 None 的情况下成为 None ?
I really like your question.我真的很喜欢你的问题。 Probably this is not exactly what you are looking for, but I have found weakref
library.可能这不是您正在寻找的内容,但我找到了weakref
库。 With it you could try to modify your code:有了它,您可以尝试修改代码:
class ListNode:
def __init__(self, val, next_=None):
self.val = val
self.next_ = next_
def get_next(self):
try:
self.next_.check()
except AttributeError: # if self.next_ exists then it does not have 'check' method.
return self.next_
except ReferenceError: # if it does not exists it will raise this exception
return None
Then instead of assigning node.next_ = next_node
, you can create weakref:然后,您可以创建weakref,而不是分配node.next_ = next_node
next_node :
node = ListNode(1)
next_node = ListNode(2)
node.next_ = weakref.proxy(next_node)
print( next_node == node.next_) # prints True
next_node = None
print(node.get_next()) # prints None
Hope this will help solve your problem!希望这将有助于解决您的问题!
Edit: I have also changed the name next
to next_
because next
is a builtin function编辑:我也改变了名字next
以next_
因为next
是一个内置函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.