我试图编写代码来保护链接列表的指针。设置器应仅指向属于同一类的实例。通常isinstance()
或type()
在定义了类之后才能工作。但是setter是该类内部的方法,因此该类尚未完全定义。
毫无疑问,type()
发出了错误。但是我不知道为什么如果从另一个类中调用,isinstance(instance, class)
会产生False
。
#define the Node class
class Node:
"""Class Node contain only data and a next pointer variables."""
def __init__(self, Data = None):
self.data = Data
self.__next = None
def getNext(self):
"""The getter"""
return self.__next
def setNext(self, NextNode):
"""The setter"""
#if possible check if NewNode is an instance of Node before pointing to it.
#I have tried "isinstance(), type(), etc. but failed.
if isinstance(NextNode, Node):
self.__next = NextNode
else:
print('The Next pointer should point to "Node" only.')
然后检查isinstance是否正常
ANode = Node((1,2,3))
BNode = Node((5,6))
ANode.setNext(BNode)
print(BNode)
print(ANode.getNext())
两张照片的地址相同
<__main__.Node object at 0x112162828>
<__main__.Node object at 0x112162828>
所以一切看起来都很好。但是,当我从下面打印的LinkedList
类进行调用时,从我的警告中可以看到,isinstance
产生False
。
class LinkedList:
"""This class is the Linked List of Node."""
def __init__(self, FirstNode = None):
"""Initialize by creating an empty List. __First hold the pointer that point to the first node."""
if FirstNode is None:
self.__first = Node(None)
self.__last = self.__first
elif type(FirstNode) is Node:
self.__first = FirstNode
self.__last = self.__first
else:
print('To create a linked-list enter nothing or a Node.')
raise TypeError
def getFirst(self):
return self.__first
def append(self, NewLastNode):
"""Add LastNode to the end of the list."""
if not isinstance(NewLastNode,Node):
raise TypeError
OldLast = self.__last
OldLast.setNext(NewLastNode)
self.__last = NewLastNode
NewLastNode.setNext(None)
def removeFirstNode(self):
"""Remove the first node (when the buffer is full)."""
OldFirst = self.__first
NewFirst = OldFirst.getNext()
if NewFirst == None:
# just clear data
OldFirst.data = None
else:
self.__first = NewFirst
del OldFirst
然后我创建一个LinkedList
类的实例
LL = LinkedList(Node((1,2)))
NewNode = Node((2.0, 3.0, -10))
当然isinstance
在这里工作正常
isinstance(NewNode,Node)
产生True
,但
LL.append(NewNode)
它将调用Node.setNext()
,在那里isinstance()
产生False
,而Node.setNext()
中的else打印出来
The Next pointer should point to "Node" only.
答案 0 :(得分:0)
给你错误的代码是这样的:
NewLastNode.setNext(None)
因为您正在尝试将下一个元素设置为不是Node
实例的对象,因此会出现错误。
我认为您可以删除此语句,因为您的self.__last
现在正确指向您的NewLastNode
。这样您的代码将变为:
def append(self, NewLastNode):
"""Add LastNode to the end of the list."""
if not isinstance(NewLastNode,Node):
raise TypeError
OldLast = self.__last
OldLast.setNext(NewLastNode)
self.__last = NewLastNode