What is the best way to create a Python object whe

2020-06-26 23:49发布

What is the best way to dynamically create a Python object instance when all you have is the Python class saved as a string?

For background, I am working in the Google Application Engine environment and I want to be able to load classes dynamically from a string version of the class.

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

标签: python
3条回答
我欲成王,谁敢阻挡
2楼-- · 2020-06-27 00:08

Simple example:

>>> solvertext1 = "def  f(problem):\n\treturn len(problem)\n"

>>> ex_string = solvertext1 + "\nanswer = f(%s)"%('\"Hello World\"')

>>> exec ex_string

>>> answer
11
查看更多
混吃等死
3楼-- · 2020-06-27 00:21

Use the exec statement to define your class and then instantiate it:

exec solvertext1
s = solver()
answer = s.solve(problem)
查看更多
家丑人穷心不美
4楼-- · 2020-06-27 00:23

Alas, exec is your only choice, but at least do it right to avert disaster: pass an explicit dictionary (with an in clause, of course)! E.g.:

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

this way you KNOW the exec won't pollute general namespaces, and whatever classes are being defined are going to be available as attributes of x. Almost makes exec bearable...!-)

查看更多
登录 后发表回答