网络接口==>获取源码字符串==>保存到本地py文件==>__import__导入==>getattr读取==>得到类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import os pth = os.path.dirname(__file__) # __import__似乎要求目标模块文件和当前程序文件在同一目录 # 这段字符串是网络接口返回的 clazz = """ class Person: def __init__(self): self.name = "张三" self.age = 30 def show(self): return "姓名:{},年龄:{}".format(self.name ,self.age) """ # 创建一个临时文件,作为__import__要读取的模块 with open(pth + "/tmp.py", "w") as f: f.write(clazz) # 读入模块 module = __import__("tmp") # 获取模块数据,得到类 Person = getattr(module, "Person") p = Person() print(p.age) print(p.show()) |
-end
声明
本文由崔维友 威格灵 cuiweiyou vigiles cuiweiyou 原创,转载请注明出处:http://www.gaohaiyan.com/2672.html
承接App定制、企业web站点、办公系统软件 设计开发,外包项目,毕设