[英]Python class written in string to literal object
I am trying to save a class written in string format to a database, then read this and load the class as literal class.我正在尝试将以字符串格式写入的 class 保存到数据库中,然后读取此文件并将 class 作为文字 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.如果我也知道如何以字符串格式保存 object 实例,那会更好,因为我也会将实例保存到数据库中,就像保存 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:
如果你有你的 class 保存在一个文件中 - 你可能有 - 你很幸运:
According to here you want to use the inspect.getsource
.根据这里你想使用
inspect.getsource
。
According to here you will then need to call the exec
function on the string to retrieve the saved class.根据此处,您将需要在字符串上调用
exec
function 以检索保存的 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.至于检索未保存在文件中的 class 的代码,我没有找到方法,第一个链接问题的答案表明没有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.