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

时间:2015-10-12 23:50:09

标签: 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?

2 个答案:

答案 0 :(得分:1)

通常,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)

答案 1 :(得分:1)

__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))

但是,如果您真正想要的是将对象保存到文件中,然后稍后再阅读,则可以使用jsonpickle之类的模块。