I need to define a new instance of a class from an informal string representation of the same type of class. What is a clean way to do this in Python?
program1.py:
fileHandle = open("filename.txt", "wb")
instance = className()
instance.a = 2
instance.b = 3.456
fileHandle.write(str(instance))
filename.txt (after running 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?
In general, the python str
function is designed for printing things in a human-readable way, not computer-readable as you want to use. If you control program1.py
, the pickle
module could fit your needs.
Program1.py:
import pickle
[rest of code unrelated to printing]
pickle.dump(instance,fileHandle)
Program2.py:
instance = pickle.load(fileHandle)
The __repr__
magic method is intended for this purpose. It should return the string that, when evaluated in a Python interpreter or source code file, would generate the same object.
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))
However, if all you really want to do is save the object to a file and then read it back in later, you could use a module like json
or pickle
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.