将类保存到二进制文件中 - Python

Save a class into a binary file - Python(将类保存到二进制文件中 - Python)
本文介绍了将类保存到二进制文件中 - Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我知道可以使用以下方法将类保存到 c++ 中的二进制文件中:

I'm aware that saving a class into a binary file in c++ is possible using:

file.write(Class_variable, size_of_class, amount_of_saves, file_where_to_save)

或类似的东西,我想在 python 中使用它,以便更轻松地写入和读取大量数据.

or something similar, and I wanted to use that in python in order to make it easier to write and read lots of data.

我试过这样做:

def Save_Game(player, room):
    address = 'Saves/player'

    file = open(address, 'wb')
    file.write(player)

    address = 'Saves/room'

    file = open(address, 'wb')
    file.write(room)

房间和玩家是class_objects.但它说:

Room and player being class_objects. But it says:

TypeError: must be convertible to a buffer, not PlayerMarty

我能做什么?

推荐答案

pickle 是你需要的.pickle 模块实现了一种基本但强大的算法,用于序列化和反序列化 Python 对象结构.这是一个例子

pickle is what you need. The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. This is an example

import pickle

class MyClass:
    def __init__(self,name):
        self.name = name
    def display(self):
        print(self.name)

my = MyClass("someone")
pickle.dump(my, open("myobject", "wb"))
me = pickle.load(open("myobject", "rb"))
me.display()

这篇关于将类保存到二进制文件中 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to find element by part of its id name in selenium with python(如何使用python在selenium中通过其id名称的一部分查找元素)
NoSuchElementException: Message: Unable to locate element while trying to click on the button VISA through Selenium and Python(NoSuchElementException:消息:尝试通过 Selenium 和 Python 单击 VISA 按钮时无法找到元素) - IT屋-程序员软件开发技术分
Selenium not able to click on Get Data button on using Python(Selenium 在使用 Python 时无法单击“获取数据按钮)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable with Selenium and Python(selenium.common.exceptions.ElementClickInterceptedException:消息:元素点击被拦截:元素不可点击
Selenium Compound class names not permitted(不允许使用硒化合物类名称)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium(selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:尝试使用 selenium 单