使用exec,您可以按照已經指出的那樣執行此操作。試試看:
>>> source_string = """
... class someClass:
... def __init__(self):
... self.s = "some String"
... def _return_s(self):
... return self.s
...
... """
>>> exec(source_string)
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'ask', 'random', 'someClass', 'source_string', 'var']
>>> x = someClass()
>>> x
<__main__.someClass object at 0x7f131424a1d0>
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_return_s', 's']
>>> x.s
'some String'
>>> x._return_s()
'some String'
我不明白你爲什麼要這樣做。爲什麼你不能正常定義類?
您可以執行任意Python源代碼字符串,請參閱http://stackoverflow.com/q/701802/3001761 – jonrsharpe
這看起來像'eval()'將用於,但'eval'是邪惡的 –
eval是沒有用於複雜的代碼,exec是 – lejlot