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

时间:2018-10-15 15:36:16

标签: python linked-list

我试图编写代码来保护链接列表的指针。设置器应仅指向属于同一类的实例。通常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.

1 个答案:

答案 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