![](/img/trans.png)
[英]Why do I get unexpected behavior in Python isinstance after pickling?
[英]Python 3 unexpected behavior with isinstance method
我看到了意外的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))
. . .
在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
為什么當兩個參數屬於同一類時,instance從不同的位置調用時會返回兩個不同的東西?
如果相關,我的目錄結構是這樣的:
sandbox.py
trees/
binary_tree.py
bst.py
util.py
在bst.py中,Bst的定義如下:
Bst(Node):
. . .
tree = Bst("A") bfs(tree, ...) def bfs(n, ...): isinstance(n, Node)
在這里, n
實際上是Bst
一個實例 , Bst
是Node
的子類。
from trees.bst import Bst isinstance(Bst, Node)
Bst
是類,而不是它的實例,因此isinstance
為False
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.