Python:如何检查输入是否是该类中类的实例?



我试图编写一个保护链表指针的代码。资源库应仅指向属于同一类的实例。 通常在定义类后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.')

然后检查 is实例是否正常工作

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()中的其他人打印出来

The Next pointer should point to "Node" only.

给你错误的一段代码是这样的:

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

相关内容

  • 没有找到相关文章

最新更新