使用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