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

一个全模块减少代码耦合性的假设

  •  1
     
  •   blackjam · 2014-08-10 09:19:23 +08:00 · 2999 次点击
    这是一个创建于 3541 天前的主题,其中的信息可能已经有所发展或是发生改变。
    ##### 外部 main.py
    import Mod

    ##### Mod目录下的__init__.py
    http://gist.github.com/b177135c5c043e5d5f90

    ##### Mod目录下的Core.py
    #encoding:utf-8
    class Core:
    """ 提供全局数据和接口 """
    pass


    例子: https://github.com/codejam1024/SM
    5 条回复    2014-08-10 14:29:58 +08:00
    datou552211
        1
    datou552211  
       2014-08-10 10:03:56 +08:00   ❤️ 1
    这很像ruby gem的风格
    ritksm
        2
    ritksm  
       2014-08-10 13:00:21 +08:00
    这样做的意义在于什么..

    Mod
    -- Core
    ---- __init__.py
    ---- Http.py
    ---- SM.py


    不是一样的效果?耦合减在哪里
    blackjam
        3
    blackjam  
    OP
       2014-08-10 13:21:44 +08:00
    @ritksm 外部自动连接全部模块并初始化,更专注的写每个模块
    ritksm
        4
    ritksm  
       2014-08-10 14:01:40 +08:00   ❤️ 1
    要自动连接全部模块的话

    from Mod.Core import *

    然后Core.__init__.py 里面写好__all__限制一下或者不写也行

    初始化你直接在某个模块的里面写,比如Http.py:

    def init_http():
    pass

    init_http()

    不就行了么
    blackjam
        5
    blackjam  
    OP
       2014-08-10 14:29:58 +08:00
    @ritksm Core类似一个空间,main.py导入Mod,Mod的__init__.py自动加载Mod目录下的所有模块并初始化到Core空间里,如Command模块,我在Test模块里调用,只需要from Mod.Core import *添加Core空间,然后Core.Command.CommandAdd("test", HookCommandTest, "test module"),就可以添加一条命令,Command基于Controller模块,这样只要提供好接口功能,则可自由组合模块,如可以把Command模块换成GUI模块
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2850 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 06:13 · PVG 14:13 · LAX 23:13 · JFK 02:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.