怎么通过isinstance(Obj,Class)验证?【isinstance】

最近有这样一个项目,这个项目可以用一个成熟的项目的构造树,读取树,再检索的过程,现在有新的需求,另一个逻辑构造同样节点结构的树,pickle序列化保存,再使用原来项目的读取、检索函数,当我完成存储正准备读取的时候,这个成熟的项目的健壮性,拒绝了我的树,这里的拒绝逻辑具体用到了instance,这是一个判断obj是不是class的实例的python内置函数,(据说,obj是继承的子类也过,感兴趣可以验证下,我这里的任务是识别为该类实例化的对象)

使用dir(my_tree)dir(original_tree)可以看到对象属性方法的不同:

复制代码
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'all_nodes', 'build_hierarchy', 'build_tree', 'create_nodes', 'layer_to_nodes', 'leaf_nodes', 'markdown_text', 'num_layers', 'parse_markdown', 'root_nodes', 'save']
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'all_nodes', 'layer_to_nodes', 'leaf_nodes', 'num_layers', 'root_nodes']

我尽可能能让我构造的类MyTree对齐原本的类Tree,对齐后重新查看:

复制代码
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'all_nodes', 'layer_to_nodes', 'leaf_nodes', 'num_layers', 'root_nodes']
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'all_nodes', 'layer_to_nodes', 'leaf_nodes', 'num_layers', 'root_nodes']

这里有很高概率可以通过isinstance(my_tree,Tree) == True,如果你和我一样仍然不通过,试试对齐模块路径,我这里成了。

不同的模块路径 :如果 Tree 类是在不同的模块中定义的,并且 pickle 在序列化时保存了模块路径信息,那么即使类名相同,如果模块路径不同,isinstance() 也可能会返回 False

python 复制代码
#pickle反序列化过程参考
SAVE_PATH = "output/chapter4_tree"
    import pickle
    from raptor.tree_structures import Tree
    with open(SAVE_PATH, "rb") as file:
                    tree = pickle.load(file)
    print(dir(tree))
    
    original_tree = Tree(all_nodes={}, root_nodes=[], leaf_nodes=[], num_layers=0, layer_to_nodes={})
    print(dir(original_tree))
    if not isinstance(tree,Tree):
        print("还得改") 
    else:
        print("成了")
python 复制代码
#pickle序列化过程参考
def save(self,tree, path):
    # 确保路径中的目录存在
    self.tree = tree
    os.makedirs(os.path.dirname(path), exist_ok=True)
    
    with open(path, 'wb') as file:
        pickle.dump(self.tree, file)
    print(f"Tree successfully saved to {path}")
相关推荐
码上淘金3 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo3 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
2301_787552873 小时前
console-chat-gpt开源程序是用于 AI Chat API 的 Python CLI
人工智能·python·gpt·开源·自动化
懵逼的小黑子3 小时前
Django 项目的 models 目录中,__init__.py 文件的作用
后端·python·django
Y3174294 小时前
Python Day23 学习
python·学习
Ai尚研修-贾莲5 小时前
Python语言在地球科学交叉领域中的应用——从数据可视化到常见数据分析方法的使用【实例操作】
python·信息可视化·数据分析·地球科学
qq_508576095 小时前
if __name__ == ‘__main__‘
python
学地理的小胖砸5 小时前
【Python 基础语法】
开发语言·python
程序员小远5 小时前
自动化测试与功能测试详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
_Itachi__5 小时前
Model.eval() 与 torch.no_grad() PyTorch 中的区别与应用
人工智能·pytorch·python