繁体   English   中英

Python class 以字符串形式写入文字 object

[英]Python class written in string to literal object

我正在尝试将以字符串格式写入的 class 保存到数据库中,然后读取此文件并将 class 作为文字 class 加载。

我怎样才能做到这一点?

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')

如果我也知道如何以字符串格式保存 object 实例,那会更好,因为我也会将实例保存到数据库中,就像保存 pickle 一样。

非常感谢。

几乎是重复的,但我不得不结合两个答案。 如果你有你的 class 保存在一个文件中 - 你可能有 - 你很幸运:

根据这里你想使用inspect.getsource

根据此处,您将需要在字符串上调用exec function 以检索保存的 class。

把东西放在一起:

import inspect

class Test:
    def __init__(self):
        self.a = 1
    def print(self):
        print(self.a)

text = inspect.getsource(Test)
exec(text)

至于检索未保存在文件中的 class 的代码,我没有找到方法,第一个链接问题的答案表明没有。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM