Python-导入模块

导入方式

  • import <模块名>
  • from <模块名> import <代码元素>
  • from <模块名> import <代码元素> as <代码元素别名>

举例

  • hello.py:

    x = "hello"
    print("x")
    
  • world.py:

    y = "world" \
        "!"
    print("y")
    
  • test.py:

    # import hello
    from hello import x
    import world
    # from world import y
    
    print(x + world.y)
    
    x
    y
    helloworld!
    

Import语句将被引用的文件执行一遍, 从而检测出被引用的模块中是否存在语法错误.

因此, 任何一个模块或者库中最好只存在函数申明、类申明、函数实现或者类实现, 因为这四种模式不会被执行.

如果你实在想在编写的模块中运行可执行的语句, 但是又不希望在被引用时执行这些语句, 可以使用python文件的魔方属性__name__.

posted @ 2022-08-04 00:43  Khrushchefox  阅读(19)  评论(0编辑  收藏  举报