gpt4 book ai didi

python - 当您将类实现存储在字符串中时,创建 Python 对象的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-28 20:11:59 24 4
gpt4 key购买 nike

当您只有将 Python 类保存为字符串时,动态创建 Python 对象实例的最佳方法是什么?

作为背景,我在 Google Application Engine 环境中工作,我希望能够从类的字符串版本动态加载类。

problem = “1,2,3,4,5”

solvertext1 = “””class solver:
def solve(self, problemstring):
return len(problemstring) “””

solvertext2 = “””class solver:
def solve(self, problemstring):
return problemstring[0] “””

solver = #The solution code here (solvertext1)
answer = solver.solve(problem) #answer should equal 9

solver = #The solution code here (solvertext2)
answer = solver.solve(problem) # answer should equal 1

最佳答案

唉,exec 是您唯一的选择,但至少要正确地避免灾难:传递一个显式字典(当然带有 in 子句)!例如:

>>> class X(object): pass
...
>>> x=X()
>>> exec 'a=23' in vars(x)
>>> x.a
23

这样你就知道 exec 不会污染一般命名空间,并且任何定义的类都将作为 x 的属性可用。 几乎 使 exec 可以忍受...!-)

关于python - 当您将类实现存储在字符串中时,创建 Python 对象的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1310254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com