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

__init__.py 除了 包的作用,还有什么?

  •  
  •   crytis · Nov 1, 2016 · 3884 views
    This topic created in 3491 days ago, the information mentioned may be changed or developed.
    这个文件里可以写代码吗?
    看 flask 的文档,把 views 拆出来,在 __init__.py 里面 app = Flask(__name__)

    然后我直接在 __init__.py 里用 main app.run(),结果都是 404.
    但是如果放到别的文件里, import app ,再 run 就可以。
    7 replies    2016-11-04 13:14:36 +08:00
    jppxhz01
        1
    jppxhz01  
       Nov 1, 2016 via Android
    可以写代码呀,在 import 包的时候就执行了
    crytis
        2
    crytis  
    OP
       Nov 1, 2016 via iPhone
    @jppxhz01 里面的代码会在 import 的时候执行?
    为啥里面运行 APP.run 不行呢
    shyling
        3
    shyling  
       Nov 1, 2016
    __all__
    phithon
        4
    phithon  
       Nov 1, 2016
    主要是 export 用,比如我写一个模块 example ,在其__init__.py 里导出一些对象,比如 session
    不管内部还是外部,要获取 session ,都直接 `from example import session` 就好了。
    crytis
        5
    crytis  
    OP
       Nov 1, 2016 via iPhone
    @shyling
    @phithon 嗯 其实我想问 为啥在里面运行 APP.run 全是 404
    ibigbug
        6
    ibigbug  
       Nov 2, 2016
    贴代码。你这样问没人答得出来。
    kitar
        7
    kitar  
       Nov 4, 2016
    建议你看下 python 的库源码,看看别人怎么用__init__
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   6181 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 83ms · UTC 03:00 · PVG 11:00 · LAX 20:00 · JFK 23:00
    ♥ Do have faith in what you're doing.