Python-Blender游戏引擎:_pickle.PicklingError:无法腌制<class'__main __。“ a =”“ class”'=“”>:在__main__上进行属性查找“一个类”失败

时间:2018-07-08 20:22:32

标签: 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'))
  

当尝试在bge中运行它时会引发该错误       但是当我用python IDLE运行它时没有问题       我设法在文件中写入腌制的类       虽然我知道通常不能腌制课       然后我什至设法打开文件,解开文件并打印       班级的属性

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

1 个答案:

答案 0 :(得分:1)

由于这在混合器中运行时有效并且仅在游戏引擎中失败,因此我认为这与在游戏引擎python绑定中进行的优化有关。

遵循handling stateful objects示例并添加自定义__getstate__也会失败,这表明游戏引擎可能实现自定义__slots__来仅提供最少的功能集。

该解决方案似乎是直接对对象__dict__进行酸洗,然后您还可以腌制新的实例__dict__

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