推荐学习书目
› 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
simple2025
0D
V2EX  ›  Python

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

  •  
  •   simple2025 · Sep 1, 2020 · 2143 views
    This topic created in 2223 days ago, the information mentioned may be changed or developed.

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

    https://www.imooc.com/read/76/article/1928
    simple2025
        3
    simple2025  
    OP
       Sep 1, 2020
    @hareandlion models 就是一个 module
    下面的文件是这样的结构

    ```
    model_user.py
    model_user_token.py
    model_log.py
    __init__.py
    ```
    Hieast
        4
    Hieast  
       Sep 2, 2020
    首先虽然你描述用的是 module,但是 3l 的例子说明其实你 import 的是 package 包,这里概念有问题。

    另外就算技术上没有问题,但是业务上为什么要这么做?
    假如业务会增长,你的 consts, models, exceptions 肯定要根据业务领域再次分成不同的包,但是 HandlerBase 应该是整个项目通用的,这里有矛盾。
    假如业务不会增长,本来也没有几个 handler,直接导入也不复杂吧?
    simple2025
        5
    simple2025  
    OP
       Sep 3, 2020
    @Hieast 就是为了导入呀
    xchaoinfo
        6
    xchaoinfo  
       Sep 4, 2020
    为了导入方便的话, 在 __init__ 重新定义 __all__ , 然后 from xxx import *
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2330 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 09:25 · PVG 17:25 · LAX 02:25 · JFK 05:25
    ♥ Do have faith in what you're doing.