现在有一个需求,就是python中使用字符串动态定义一个类,并随后使用其中的方法。
# /test.py
# coding=utf-8
content = '''
class MyClass:
def __init__(self):
self.name = None
self.age = None
def do():
return MyClass()
'''
exec content
print do()
# 或者最后一句话改成exec("print do()")
直接运行这段代码是没有问题的,得到了输出<__main__.MyClass instance at 0x000000000243EB88>
。
首先定义另一个actor.py
文件:
# /actor.py
# coding=utf-8
def execute(content):
exec content
return do()
然后定义test.py
文件:
# /test.py
# coding=utf-8
import actor
content = """
class MyClass:
def __init__(self):
self.name = None
self.age = None
def do():
return MyClass()
"""
print actor.execute(content)
运行test.py
文件,会出现NameError: global name 'MyClass' is not defined
。
我的需求就是,定义一个模块,在这个模块的函数中执行一段指定的字符串,动态定义一个类,并且需要调用这个类,现在遇到的问题如上所示,求助啊。。。
First of all "exec" is not a recommended method because it will bring some problems:
Some modules based on the __module__ attribute will fail, such as pickle, inspect, pydoc, etc.
Memory leak
namespace and module shutdown behavior issue
For a detailed description of these issues, please refer to: http://lucumr.pocoo.org/2011/...
If you insist on doing this, the following code can provide some reference:
tester.py
actor.py
Create a class dynamically
You may consider using exec, maybe because you are not exposed to the advanced features of python