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
chenqh
V2EX  ›  Python

在 Python 里面把 module 设置成类的变量有什么问题吗?

  •  
  •   chenqh · 2020-09-01 09:35:44 +08:00 · 1301 次点击
    这是一个创建于 1304 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我用的是 tornado

    我定义了一个 HandlerBase

    from proj import consts, models, exceptions
    from tornado import web
    class HandlerBase(web.RequestHandler):
       f_consts= consts
       f_models = models
       f_exceptions = exceptions
    
    

    这个样子是有什么问题吗?

    我的目的是因为

    基本上 Handler 都需要用到这些 module,

    因为不知道这么做有什么问题,我现在只在测试里面这么写了

    6 条回复    2020-09-04 16:11:18 +08:00
    hareandlion
        1
    hareandlion  
       2020-09-01 09:47:05 +08:00   ❤️ 1
    被 import 的“models”是个单例对象,作为 HandlerBase 中的类变量,被多个`HandlerBase`同时访问时可能造成内存泄漏,如果已经做过相关处理,或者 models 是公共数据,本就允许这样使用,那没问题
    fasionchan
        2
    fasionchan  
       2020-09-01 09:49:14 +08:00   ❤️ 1
    一般没有什么问题。但是,如果这些变量是描述符(descriptor,实现了__get__ __set__ __del__ 魔术方法)的话,属性查找行为需要留意。具体可以研究下 Python 类机制以及数据描述符的特性:

    https://www.imooc.com/read/76/article/1928
    chenqh
        3
    chenqh  
    OP
       2020-09-01 09:59:34 +08:00
    @hareandlion models 就是一个 module
    下面的文件是这样的结构

    ```
    model_user.py
    model_user_token.py
    model_log.py
    __init__.py
    ```
    Hieast
        4
    Hieast  
       2020-09-02 23:40:43 +08:00
    首先虽然你描述用的是 module,但是 3l 的例子说明其实你 import 的是 package 包,这里概念有问题。

    另外就算技术上没有问题,但是业务上为什么要这么做?
    假如业务会增长,你的 consts, models, exceptions 肯定要根据业务领域再次分成不同的包,但是 HandlerBase 应该是整个项目通用的,这里有矛盾。
    假如业务不会增长,本来也没有几个 handler,直接导入也不复杂吧?
    chenqh
        5
    chenqh  
    OP
       2020-09-03 09:52:20 +08:00
    @Hieast 就是为了导入呀
    xchaoinfo
        6
    xchaoinfo  
       2020-09-04 16:11:18 +08:00
    为了导入方便的话, 在 __init__ 重新定义 __all__ , 然后 from xxx import *
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   948 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 21:01 · PVG 05:01 · LAX 14:01 · JFK 17:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.