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

python import 导入模块的时候为什么引用不了子模块?

  •  
  •   vtoexsir · Dec 10, 2016 · 5715 views
    This topic created in 3474 days ago, the information mentioned may be changed or developed.

    比如导入结巴分词,代码如下:
    import jieba # 引入母模块-很土的名字,不知道是否有专业名字?
    然后直接使用结巴的子模块 posseg 来标注词性,代码如下:
    jieba.posseg.cut('中文词性标注') # 这句报异常: #=>AttributeError: 'module' object has no attribute 'posseg'

    必须这样导入子模块,才能使用:
    from jieba import posseg
    posseg.cut('中文词性标注') # 这句正常调用

    看到常说推荐直接导入母模块,以防止命名空间污染;而且一般如:
    from a import b
    b.func('中文词性标注')
    这样格式的代码,都能转为这样来使用:
    import a
    a.b.func('中文词性标注')
    但为什么 jieba 结巴分词却不能这样呢?这是什么原因呢?
    感谢您的回复!

    2 replies    2016-12-10 09:39:04 +08:00
    wwqgtxx
        1
    wwqgtxx  
       Dec 10, 2016 via iPhone   ❤️ 1
    这个第三方模块在__init__.py 中做处理才能那么用
    hosiet
        2
    hosiet  
       Dec 10, 2016 via Android   ❤️ 2
    如果 a 是个目录, b 是个 b.py 文件, func 是 b.py 里的函数, a 目录里有空的 __init__.py

    import a # 没问题
    import a.b # 没问题,会在这一句找 a/b.py
    result = a.b.func() # 正常

    重来一遍:
    import a # 没问题
    result = a.b.func() # 不行, a 下面并没有 b
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3637 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 04:53 · PVG 12:53 · LAX 21:53 · JFK 00:53
    ♥ Do have faith in what you're doing.