V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ruandao
V2EX  ›  Python

Python 动态生成的类 怎么导出到 文件中

  •  
  •   ruandao · 2019-07-02 15:24:28 +08:00 · 1473 次点击
    这是一个创建于 1753 天前的主题,其中的信息可能已经有所发展或是发生改变。

    用 type 生成的类, 要怎么导出到 xxx.py 文件中

    cls = type("ClsName", (object, ), attr)
    code = xxxGetSource(cls)
    writeToFile(code, "moduleName/ClsName.py")
    

    django,makemigrations 的时候,需要把 Model 的继承的父类 注册到 migrations 的文件中, 然后, 我的一些 Model 继承的类是动态生成的 譬如:

    class XXXModel(GenerateCls({ .... }),
               models.Model):
    pass
    
    def GenerateCls(....):
        ...
        return type(name, bases, attr)
    
    第 1 条附言  ·  2019-07-03 15:21:31 +08:00
    用 mixin + __getattr__ 的方式绕过原来的问题了

    谢谢
    2 条回复    2019-07-03 09:08:30 +08:00
    ebingtel
        1
    ebingtel  
       2019-07-03 08:40:34 +08:00   ❤️ 1
    code = xxxGetSource(cls),在里面遍历属性、通过 inspect.getsource 拿到 function 的源码……其他的就是格式化的问题了
    matrix273
        2
    matrix273  
       2019-07-03 09:08:30 +08:00 via Android   ❤️ 1
    pickle 这个库可以吗?不是很懂。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4735 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 09:57 · PVG 17:57 · LAX 02:57 · JFK 05:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.