I am trying to save a class written in string format to a database, then read this and load the class as literal class.
How can I do this?
test = """
class Test:
def __init__(self, test_name):
self.test_name = test_name
def print_name(self):
print(self.test_name)
"""
Test = eval(test)
test_obj = Test(test_name='test1')
It would be better together if I also know how to save the object instance in string format since I will save the instance to the database as well, like saving pickle.
Many thanks.
Almost a duplicate but I had to combine two answers. If you have your class saved in a file - which you probably have - you are in luck:
According to here you want to use the inspect.getsource
.
According to here you will then need to call the exec
function on the string to retrieve the saved class.
Putting things together:
import inspect
class Test:
def __init__(self):
self.a = 1
def print(self):
print(self.a)
text = inspect.getsource(Test)
exec(text)
As for retrieving a code of a class that is not saved in the file I didn't find a way and the first linked question's answer suggests that there isn't any.
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.