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

初识 Python 对包和模块引入的疑惑

  •  
  •   SimpKae · Dec 29, 2015 · 3649 views
    This topic created in 3814 days ago, the information mentioned may be changed or developed.

    from tkinter import *
    import tkinter.messagebox as messagebox

    以上代码中 tkinter 是一个包,然后第一句把包里面的所有模块引入进来。

    第二句 messagebox 是 tkinter 中的一个模块,按我的理解,第一句已经全部引入进来了,为什么还要把 messagebox 单独引入才能正常使用了。而不写第二句,我尝试用 tkinter.messagebox.func(),或者 messagebox.func()调用都报错 not define 。

    麻烦 pythoner 们授业解惑,小弟不甚感激

    7 replies    2015-12-31 18:47:06 +08:00
    yangtukun1412
        1
    yangtukun1412  
       Dec 29, 2015   ❤️ 1
    from tkinter import * 引入的是 tkinter/__init__.py 中的内容,而在 __init__.py 中没有 import messagebox ,所以没有引入。
    nooper
        2
    nooper  
       Dec 29, 2015   ❤️ 1
    不要用 import *
    要了解 packages 结构。
    分绝对导入,相对导入,还有神吗导入。
    你可以理解一下 locals () 和 globals ()
    比如你导入的时候可以写成
    from .packages import mydev
    或者 from apps.packages import mydev
    等等,避免循环调用会非常的影响性能,
    千万不要再函数里方法里面写 import ,如果这么写代码就可以说写得很垃圾了,一开始就没有设计好。
    SimpKae
        3
    SimpKae  
    OP
       Dec 29, 2015
    @yangtukun1412 非常感謝,小弟顿时茅舍顿开呀,看來得学的更细致些。
    SimpKae
        4
    SimpKae  
    OP
       Dec 29, 2015
    @nooper 謝謝您的指點,學習了。
    garfieldWu
        5
    garfieldWu  
       Dec 29, 2015
    补充 nooper ,不同导入路径的同一个包所占的内存空间也是不同的,就是由于 locals()和 globals()
    qnnnnez
        6
    qnnnnez  
       Dec 31, 2015
    @nooper 当循环 import 不可避免的时候, import 就应该写在函数里。
    nooper
        7
    nooper  
       Dec 31, 2015
    @qnnnnez 我就从来没有这么写过,这样写的绝大多数是设计缺陷。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1035 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 19:22 · PVG 03:22 · LAX 12:22 · JFK 15:22
    ♥ Do have faith in what you're doing.