gpt4 book ai didi

python - 如何在Python中反转str(class)?

转载 作者:行者123 更新时间:2023-12-01 04:26:16 25 4
gpt4 key购买 nike

我需要根据相同类型类的非正式字符串表示来定义类的新实例。在 Python 中执行此操作的干净方法是什么?

程序1.py:

fileHandle = open("filename.txt", "wb")
instance = className()
instance.a = 2
instance.b = 3.456
fileHandle.write(str(instance))

filename.txt(运行program1.py后):

<className a=2, b=3.456>

程序2.py:

instance = className()
with open("filename.txt", "r") as fileHandle:
for fileLine in fileHandle:
##### How do I grab the contents of the file line and get them in variables? #####
(instance.a, instance.b) = magicFunction(fileLine)
# I seem to have forgotten the contents of magicFunction(). Can someone remind me?

最佳答案

一般来说,python str 函数旨在以人类可读的方式打印内容,而不是您想要使用的计算机可读方式。如果您控制 program1.py,则 pickle 模块可以满足您的需求。

Program1.py:
import pickle
[rest of code unrelated to printing]
pickle.dump(instance,fileHandle)
Program2.py:
instance = pickle.load(fileHandle)

关于python - 如何在Python中反转str(class)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33091960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com