推荐学习书目
› 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 · 4262 views
    This topic created in 3664 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
    jppxhz01
    Nov 1, 2016 via Android
    1
    可以写代码呀,在 import 包的时候就执行了
    crytis
    crytis
    OP
    Nov 1, 2016 via iPhone
    2
    @jppxhz01 里面的代码会在 import 的时候执行?
    为啥里面运行 APP.run 不行呢
    shyling
    shyling
    Nov 1, 2016
    3
    __all__
    phithon
    phithon
    Nov 1, 2016
    4
    主要是 export 用,比如我写一个模块 example ,在其__init__.py 里导出一些对象,比如 session
    不管内部还是外部,要获取 session ,都直接 `from example import session` 就好了。
    crytis
    crytis
    OP
    Nov 1, 2016 via iPhone
    5
    @shyling
    @phithon 嗯 其实我想问 为啥在里面运行 APP.run 全是 404
    ibigbug
    ibigbug
    Nov 2, 2016
    6
    贴代码。你这样问没人答得出来。
    kitar
    kitar
    Nov 4, 2016
    7
    建议你看下 python 的库源码,看看别人怎么用__init__
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2077 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 12:06 · PVG 20:06 · LAX 04:06 · JFK 07:06
    ♥ Do have faith in what you're doing.