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

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

  •  
  •   crytis · 2016-11-01 18:03:25 +08:00 · 3065 次点击
    这是一个创建于 2731 天前的主题,其中的信息可能已经有所发展或是发生改变。
    这个文件里可以写代码吗?
    看 flask 的文档,把 views 拆出来,在 __init__.py 里面 app = Flask(__name__)

    然后我直接在 __init__.py 里用 main app.run(),结果都是 404.
    但是如果放到别的文件里, import app ,再 run 就可以。
    7 条回复    2016-11-04 13:14:36 +08:00
    jppxhz01
        1
    jppxhz01  
       2016-11-01 18:28:03 +08:00 via Android
    可以写代码呀,在 import 包的时候就执行了
    crytis
        2
    crytis  
    OP
       2016-11-01 19:25:29 +08:00 via iPhone
    @jppxhz01 里面的代码会在 import 的时候执行?
    为啥里面运行 APP.run 不行呢
    shyling
        3
    shyling  
       2016-11-01 19:31:37 +08:00
    __all__
    phithon
        4
    phithon  
       2016-11-01 20:36:52 +08:00
    主要是 export 用,比如我写一个模块 example ,在其__init__.py 里导出一些对象,比如 session
    不管内部还是外部,要获取 session ,都直接 `from example import session` 就好了。
    crytis
        5
    crytis  
    OP
       2016-11-01 22:17:55 +08:00 via iPhone
    @shyling
    @phithon 嗯 其实我想问 为啥在里面运行 APP.run 全是 404
    ibigbug
        6
    ibigbug  
       2016-11-02 03:13:41 +08:00
    贴代码。你这样问没人答得出来。
    kitar
        7
    kitar  
       2016-11-04 13:14:36 +08:00
    建议你看下 python 的库源码,看看别人怎么用__init__
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1064 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 22:17 · PVG 06:17 · LAX 15:17 · JFK 18:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.