使用isinstance方法的Python 3意外行为

Cha*_*ley -1 python inheritance subclass python-3.x

我看到了一些我不希望的isinstance方法的奇怪行为.有人可以帮我确定为什么会这样吗?

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

问题是:Bst类(BST节点)是Node的子类(通用二叉树节点).我的实用程序方法有一些检查以确保它们的参数是Node或其子类型的实例:

def bfs(n: Node, process=None):
    . . . 
    assert isinstance(n, Node)
    # print for debugging
    print("util.py:", isinstance(n, Node))
    . . . 
Run Code Online (Sandbox Code Playgroud)

在bfs方法中,断言通过以下调用,然后打印打印:

tree = Bst("A")
bfs(tree, lambda n: print(n.data, end=' ')) # Ignore the implementation, just know this enters the method
util.py: True
Run Code Online (Sandbox Code Playgroud)

正如所料.但是,在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
Run Code Online (Sandbox Code Playgroud)

为什么isinstance在从不同位置调用时会返回两个不同的东西,即使这两个参数属于同一个类?

如果它相关,我的目录结构是这样的:

sandbox.py
trees/
    binary_tree.py
    bst.py
    util.py
Run Code Online (Sandbox Code Playgroud)

在bst.py中,Bst定义如下:

Bst(Node):
    . . . 
Run Code Online (Sandbox Code Playgroud)

mkr*_*er1 5

tree = Bst("A")
bfs(tree, ...)

def bfs(n, ...):
    isinstance(n, Node)
Run Code Online (Sandbox Code Playgroud)

在这里,n实际上是一个实例Bst,的一个子类Node.

from trees.bst import Bst
isinstance(Bst, Node)
Run Code Online (Sandbox Code Playgroud)

Bst是类,而不是它的实例,所以isinstanceFalse.