Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用isinstance方法的Python3意外行为_Python_Python 3.x_Inheritance_Subclass - Fatal编程技术网

使用isinstance方法的Python3意外行为

使用isinstance方法的Python3意外行为,python,python-3.x,inheritance,subclass,Python,Python 3.x,Inheritance,Subclass,我在isinstance方法中看到了一些我意想不到的奇怪行为。有人能帮我确定为什么会发生这种情况吗 我有一个模块sandbox.py,我在创建模块时使用它来修补模块。我还有一个二叉树类binary_tree.py和一个BST类BST.py,它继承自二叉树实现并添加了树排序的约束。我还有一些在树上操作的实用方法,如BFS、DFS等 问题在于:类Bst(Bst节点)是节点(通用二叉树节点)的子类。我的实用程序方法进行了一些检查,以确保其参数是节点或其子类型的实例: def bfs(n: Node,

我在isinstance方法中看到了一些我意想不到的奇怪行为。有人能帮我确定为什么会发生这种情况吗

我有一个模块sandbox.py,我在创建模块时使用它来修补模块。我还有一个二叉树类binary_tree.py和一个BST类BST.py,它继承自二叉树实现并添加了树排序的约束。我还有一些在树上操作的实用方法,如BFS、DFS等

问题在于:类Bst(Bst节点)是节点(通用二叉树节点)的子类。我的实用程序方法进行了一些检查,以确保其参数是节点或其子类型的实例:

def bfs(n: Node, process=None):
    . . . 
    assert isinstance(n, Node)
    # print for debugging
    print("util.py:", isinstance(n, Node))
    . . . 
在bfs方法中,断言通过以下调用传递,然后打印:

tree = Bst("A")
bfs(tree, lambda n: print(n.data, end=' ')) # Ignore the implementation, just know this enters the method
util.py: True
正如所料。但是,在sandbox.py中,相同的调用打印False:

from trees.binary_tree import Node
from trees.util import *
from trees.bst import Bst

print("sandbox.py:", isinstance(Bst, Node))
sandbox.py: False
为什么isinstance在从不同位置调用时返回两个不同的东西,即使这两个参数属于同一个类

如果相关,我的目录结构如下:

sandbox.py
trees/
    binary_tree.py
    bst.py
    util.py
在bst.py中,bst的定义如下:

Bst(Node):
    . . . 
这里,
n
实际上是
Bst
的一个实例,Bst是
节点
的一个子类


Bst
是类,而不是它的实例,因此
isinstance
False

对不起,我错过了您使用的
isinstance(Bst,Node)
Bst
是类,而不是实例。那么你的断言,即使这两个参数属于同一类?不是真的。啊,愚蠢的错误。在这种情况下,我应该使用issubclass。
tree = Bst("A")
bfs(tree, ...)

def bfs(n, ...):
    isinstance(n, Node)
from trees.bst import Bst
isinstance(Bst, Node)