我需要将字符串对象位置转换为对象。我的代码是:
class Dog:
def __init__(self,name):
self.name= name
def bark(self):
print('BAR')
b=''
a=Dog('Test')
print(a)
with open('Dog.txt','w') as file:
file.write(str(a))
with open('Dog.txt','r') as file:
b=file.read()
b=repr(b)
print(b)
b.bark()
我保存了对象a
在 Dog.txt
文件<__main__.Dog object at 0x0000024E1C7AFE80>
现在我想获取该字符串并将其转换为一个对象,这样我就可以使用 bark
方法。
我该怎么做
最佳答案
您无法从字符串表示形式中恢复对象。您应该在将对象转储到文件之前序列化该对象。您可以使用 pickle
为此
>>> a
<__main__.Dog object at 0x7f6d4ee8fb38>
>>>
>>> pickle.dump(a, open('Dog.txt', 'wb'))
>>> b = pickle.load(open('Dog.txt', 'rb'))
>>> b
<__main__.Dog object at 0x7f6d4ee8fac8>
>>> b.bark()
BAR
关于python - 如何将字符串对象位置更改为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52235173/