[英]How do I reverse str(class) in Python?
我需要从相同类型的类的非正式字符串表示形式定义一个新的类实例。 用Python执行此操作的干净方法是什么?
program1.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>
program2.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)
__repr__
魔术方法就是为此目的而设计的。 它应该返回在Python解释器或源代码文件中求值时将生成相同对象的字符串。
class className:
def __init__(self, a=0, b=0):
self.a = a
self.b = b
def __repr__(self):
return 'className(a={}, b={})'.format(self.a, self.b)
instance = className()
instance.a = 2
instance.b = 3.456
print(repr(instance))
with open("filename.txt", "w") as fileHandle:
fileHandle.write(repr(instance))
with open("filename.txt", "r") as fileHandle:
my_instance = eval(fileHandle.read())
print(repr(my_instance))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.