I need to convert string object location to an object. My code is:
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()
I saved the object a
in a Dog.txt
file <__main__.Dog object at 0x0000024E1C7AFE80>
and now i want to take that string and convert it to an object so I can use the bark
method with it.
How can I do this
you can use PyYAML:
and dump and load data from yaml files:
now dump you object to the
yaml
:inside the
data.yml
you will see:and now load:
Both Bear Brown and Sunitha fail to mention that the loading they propose to do can be unsafe. For PyYAML this is clearly indicated at the start of the tutorial:
Pickle has a similar warning:
At least using YAML, it is not necessary to run any risks now or in the future.
First do:
Then:
which gives:
Notes:
.yaml
as the file extension for files containing YAML.yaml_tag =
" line, to use a different tag in YAML document than the default (i.e. your class name)__main__
in the YAML file, which is essential if you ever decide to move the class definition to a different file.(Disclaimer: I am the author of
ruamel.yaml
)You cannot recover an object from its string representation. You should instead serialize the object before dumping it to the file. You can use
pickle
for this