Python - Blender Game Engine : _pickle. PicklingError: Can't pickle <class '__main__."a class "'>: attribute lookup "a class"on __main__ failed

标签 python pickle blender

import pickle

class NoClass():
    def __init__(self, name, level, cls, time_played):
        self.name = name
        self.level = level
        self.cls = cls
        self.time_played = time_played

def Write_char_file(registered_username):
    avatar = NoClass('',1,'',0) #--------i am trying to pickle and write this
    a = str('Characters\%s.txt' % registered_username) #---- the saving file
    f = open(a, 'wb')
    f.write(pickle.dumps(avatar))
    f.close()

def Asign_to_slot(char_lst):
    pass

Asign_to_slot(Write_char_file('my_name'))

When trying to run this in bge it raises that error BUT when i run it with python IDLE there isn't a problem and i manage to write the pickled class in the file though i know classes usually can't be pickled then i even manage to open the file, unpickle it and print the class' attributes

"_pickle.PicklingError: Can't pickle <class '__main__.NoClass'>: attribute lookup NoClass on __main__ failed"

最佳答案

由于这在 blender 中运行时有效并且仅在游戏引擎中失败,我认为这与游戏引擎 python 绑定(bind)中的优化有关。

handling stateful objects 之后示例和添加自定义 __getstate__ 也失败,表明游戏引擎可能实现自定义 __slots__仅提供最小的功能集。

解决方案似乎是直接 pickle 对象 __dict__,然后您还需要 unpickle 到新实例 __dict__

f.write(pickle.dumps(avatar.__dict__))

关于Python - Blender Game Engine : _pickle. PicklingError: Can't pickle <class '__main__."a class "'>: attribute lookup "a class"on __main__ failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51235713/

相关文章:

ios - SCNAnimationPlayer 开始播放手势动画

python - Discord.py 获取 channel 名称和服务器名称返回错误消息

python - 如何在 Pandas 数据框中选择两个日期内的行?

python - 如何洗牌 Dask 包中的元素

python - 未经授权与谷歌日历 API v3 交互

tensorflow - 如何通过 tensorflow 的 tf.data API 加载 pickle 文件

python - 我可以像将 .mat 文件拖放到 Matlab 中一样将 pickle 文件拖放到 PyCharm 中吗?

three.js - 将带有纹理的简单模型从 Blender 导出到 Three.js

python - 如何在 Python 中修复此 unicode/cPickle 错误?

python - 在 Blender 中创建拼图球体的方法是什么?