[英]"Can't get attribute" when Pickling Object
My save code is written as so in a file called 'MachLearn.py':我的保存代码是这样写在一个名为“MachLearn.py”的文件中的:
Whilst looking for this code I find out I accidentally overwrote it with an old version:/.在寻找这段代码时,我发现我不小心用旧版本覆盖了它:/. It was essentially structured like this:它的结构基本上是这样的:
class attibuteGenerator():
def __init__(self):
#more class stuff
def returnAttributes(self, rating, position):
#func stuff
if __name__ = "__main__":
ag = attributeGenerator():
with open('attributeGenerator_pickle', 'wb') as f:
pickle.dump(f, ag)
My open code is written as so in a file called "mainGame.py"我的开放代码是这样写在一个名为“mainGame.py”的文件中的
def main():
with open('attributeGenerator_pickle', 'rb') as f:
bob = pickle.load(f)
print(bob.returnAttributes(34, "LW"))
if __name__ == "__main__":
main()
This type of error arises when you attempt to unpickle an object, such as a class instance, and you don't have access to the relevant class in your current Python session. This type of error arises when you attempt to unpickle an object, such as a class instance, and you don't have access to the relevant class in your current Python session. You should reimport the packages you were using to generate the objects that you pickled.您应该重新导入您用来生成您腌制的对象的包。
The following minimal script will reproduce this problem:以下最小脚本将重现此问题:
import pickle
class my_class():
def __init__(self):
self.x = 2
inst = my_class()
with open('file.dat', 'wb') as f:
pickle.dump(inst, f); f.close()
del my_class # Deletes the class and causes the problem
with open('file.dat', 'rb') as f:
new_inst = pickle.load(f); f.close()
with error:有错误:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-10-6571eae10a31> in <module>
12
13 with open('file.dat', 'rb') as f:
---> 14 new_inst = pickle.load(f); f.close()
AttributeError: Can't get attribute 'my_class' on <module '__main__'>
This can be resolved by removing the line: del my_class
.这可以通过删除以下行来解决: del my_class
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.